Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying With MongoDate vs UTCDateTime

After upgrading to the new Mongo Driver for PHP, I am facing the problem of sorting and querying dates.

The old driver used: http://php.net/manual/en/class.mongodate.php which stored dates in a MongoDate object in seconds.

The new driver: http://php.net/manual/en/class.mongodb-bson-utcdatetime.php stores the date in a different format and stores it in milliseconds.

The has rendered querying with $gte or $lte useless. Example:

$collection -> find(array('start_date' => array('$gte' => new MongoDate())));

$collection -> find(array('start_date' => array('$gte' => new MongoDB\BSON\UTCDateTime())));

These two do not return the same result. With all the old data, how can I safely still query with both MongoDate and UTCDateTime?

like image 875
Devin Dixon Avatar asked Mar 03 '16 15:03

Devin Dixon


1 Answers

You need to pass the time in milliseconds instead of seconds, and everything will keep working like before:

$time = time();
$cursor = $collection->find(['start_date' => ['$gte' => new MongoDB\BSON\UTCDateTime($time * 1000)]]);
like image 193
cyrodiil Avatar answered Oct 01 '22 08:10

cyrodiil