Idan
Idan

Reputation: 432

MongoDB PHP Driver: Date search not working

I am migrating to PHPLIB from the old MongoDB driver. Unfortunately, I am running into issues attempting to convert date searches. I am trying to retrieve documents that were added to the database from a certain date (yesterday), however, when I perform a search, I'm getting back the count for all the records regardless of the value in 'added_on'. Not sure what I'm doing wrong.

    $collection = $mongo->getCollection("records");
$yesterday = new DateTime(date('Y-m-d').' 00:00:00');
$dateFrom = new MongoDB\BSON\UTCDateTime($yesterday->format('U'));
    $response = $collection->count(['added_on' => ['$gte' => $dateFrom], 'instance' => $element, 'invisible' => false]);

var_dump of UTCDateTime shows a valid value:

object(MongoDB\BSON\UTCDateTime)#477 (1) { ["milliseconds"]=>
string(10) "1515954053" }

Example of a document expected to return:

{ "_id" : ObjectId("5a5badcffe23a278e2bb739a"), "instance" : ObjectId("591555806803fa06650b474c"), "added_on" : ISODate("2018-01-14T23:25:55Z"), "invisible" : false, "reviewed" : true }

Any help would be appreciated.

UPDATE: Removing the variable that is sent to the UTCDateTime object like this:

$dateFrom = new MongoDB\BSON\UTCDateTime();

works (as can be seen above I've added one record in the future). Problem is when I send the variable to specify the timestamp that I need.

Upvotes: 2

Views: 1367

Answers (1)

Idan
Idan

Reputation: 432

Was able to find the issue - this behavior is caused when MongoDB\BSON\UTCDateTime receives a value generated by strtotime. The value appears to be valid (no errors are generated), but because it represents and not milliseconds, it does not behave as expected.

I've added the following function to a custom MongoDB class I'm using:

public function date($timestamp) {
    $timestamp = strtotime($timestamp) * 1000;
    $object = new MongoDB\BSON\UTCDateTime($timestamp);
    return $object;
}

Then I just call:

$response = $collection->count(['added_on' => ['$lt' => $mongo->date($yesterday->format('Y-m-d H:i:s'))], 'instance' => $element, 'invisible' => false]);

$mongo being the object of the custom class.

Upvotes: 5

Related Questions