1

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);
}
Just Ice
  • 179
  • 1
  • 1
  • 11

2 Answers2

2

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

Harshil
  • 883
  • 1
  • 8
  • 25
  • 1
    @JustIce looks like you have the solution now, and it looks like the problem was same. the new MongoDate() will give object with current date new MongoDate(strtotime($inputDate)) you have and option of using some $inputDate which can be a String with Date Format . I have updated my answer for a more clear view – Harshil Jul 27 '16 at 07:44
0

For those who landed here through the search, as I did, a current solution (2021) can be found here in the meantime: https://www.php.net/manual/en/class.mongodb-bson-utcdatetime.php

Please note the first comment with the milliseconds. Maybe it will save you time when troubleshooting ;-)

Guido S
  • 106
  • 3