Reputation: 415
Hi guys I am new to mongodb and facing some problem while comparing dates in my collection. I have a collection of events with dateCreated field storing new MongoDate() as
"dateCreated": ISODate("2013-11-13T05: 23: 45.0Z")
Now I want one of the event created today. For this I was trying with query in yii framework as
$db->event->findOne(array('dateCreated' => new MongoDate()));
But it return null which I guess due to failing in comparing time values stored within dateCreated. So can any one suggest how to compare only date not time with MongoDate().
Thanks in advance.
Upvotes: 0
Views: 2008
Reputation: 1636
To query for something created today, you'll want to use the Mongo $gt
and $lt
operators to search for a dateCreated key within the bounds of "today" in PHP:
$db->event->findOne(array('dateCreated' => array('$gt' => new MongoDate(strtotime("midnight")), '$lt' => new MongoDate(strtotime("11:59PM")))));
Upvotes: 2
Reputation: 222751
This returns null because you are searching for a collection which was created just right now.
You have too look for range queries with date.
So you need to modify it like this:
$db->event->findOne(
array('dateCreated' => array(
'$gte' => timestamp of the current day
))
);
As far as I understood you can find timestamp of a current day this way:
mktime(0, 0, 0, date('n'), date('j'));
but I might be wrong on this part.
Upvotes: 0