MongoDB ISODate query with PHP

好久不见. 提交于 2020-01-05 07:17:31

问题


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);
}

回答1:


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



来源:https://stackoverflow.com/questions/38563329/mongodb-isodate-query-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!