Osama Jetawe
Osama Jetawe

Reputation: 2705

How to query mongodb Date using php

I need to convert this query from php to mongoDB query

$query = "select * from table where data_added like '%data%';

I have date stored in variable

$date = "2013-09-02";

and in my mongo Document the date sorted as :

$dateAdded = new MongoDate(strtotime('2013-09-02 12:21:55'));

I tried

$date = new MongoDate(strtotime("$date"));

$mongo->find(array('date_added'=>array('$lt'=>$date)));

and 
$mongo->find(array('date_added'=>$date));

but without success .

so I need to query usin (Y-m-d) not (Y-m-d h:i:s) so how to use LIKE query for data in mongo

Thanks

Upvotes: 3

Views: 12067

Answers (1)

bjori
bjori

Reputation: 2104

You need to do a range query. Create a timestamp, for example using strtotime(), to get the unix timestamp at the start of the day, and another one and the end of the day.

Depending on if you want these two ends inclusive or exclusive, you then use

// Both points/seconds inclusive
->find(array("date" => array('$gte' => $startOfDay, '$lte' => $endOfDay)));
// Both seconds exclusive
->find(array("date" => array('$gt' => $startOfDay, '$lt' => $endOfDay)));

See http://cookbook.mongodb.org/patterns/date_range/

Upvotes: 2

Related Questions