Search code examples
phpmongodbisodatemongodate

MongoDB ISODate query with PHP


I am trying to retrieve data from mongo collection based on date, I want to get data where the date is greater or equal to the present day's date (i.e. the date under the data field). However I can't seem to understand why my query returns nothing (empty mongo object). Below is my code:

Array struct/content:

{ 
"_id" : ObjectId("990093409187049704809d"), 
"type" : "number 1 champion", 
"entryDate" : ISODate("2016-05-12T10:55:55.000+0000"), 
"requester" : {
    "cn" : "Torgue", 
    "username" : "tg"
}, 
"data" : {
    "office" : "Badass Crater of Badassitude",  
    "name" : {
        "firstname" : "Salvador", 
        "middlename" : "A", 
        "surname" : "Gunzerker"
    }, 
    "date" : ISODate("2016-05-23T23:00:00.000+0000"), 
}, 
"index" : "1"
}

PHP query:

$today =  date(DATE_ISO8601, (new MongoDate())->sec);
$str = $col1->find(array('type' => 'number 1 champion', 'data.date'=>array ('gte'=>$today))); 
print_r($str);

Please can anyone point me in the right direction or explain to me what to do in order to get the right output.

For anyone who has same problem, below is the solution:

$query = array('type' => 'number 1 champion', 'data.date'=>array ('$gte'=>new mongoDate()));
$str = $col1->find($query);

then loop to view results:

echo '<pre>';
foreach($str as $doc){
  print_r($doc);
}

Solution

  • You have to use MongoDate object to query.

    For current date you may use new MongoDate() which make MongoDate initialize with current Date

    If you want to pass some custom Date you may use strtotime to convert String to Date type

    $stringtime = "2016-04-09 00:00:00"
    
    $inputdate = strtotime($stringtime)
    

    and then finally passing it to MongoDate contructor to get relevant object.

    new MongoDate($inputdate)
    

    refer PHP Docs