1

I have the following MongoDBdata:

{
  "_id": ObjectId("5ae..."),
  "name": "John",
  "startdate": ISODate("2018-05-10T00:00:00Z"),
  "enddate": ISODate("2018-05-12T00:00:00Z")
}

I'm trying to query by typing the period in a form, expecting to get the result by the following logic: startdate<= the typed end date AND enddate >= the typed initial date.

I send the typed dates by ajax using the following format: "YYYY-MM-DD".

In PHP, I try this:

$initialdate = new MongoDB\BSON\UTCDatetime(strtotime($_POST['startdate'] . " 00:00:00"));
$enddate = new MongoDB\BSON\UTCDatetime(strtotime($_POST['enddate'] . " 00:00:00"));

And then I try this query:

$query = ['startdate' => ['$lte' => $initialdate], 'enddate' => ['$gte' => $enddate]];

Unfortunattely I get no results.

How can I execute this query correctly?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Diego de Lima
  • 471
  • 2
  • 7
  • 15
  • The [`strtotime()`](http://php.net/manual/en/function.strtotime.php) function returns "seconds since epoch" where the [`UTCDateTime`](http://php.net/manual/en/class.mongodb-bson-utcdatetime.php) function expects "milliseconds since epoch". You need to multiply by `1000` to get the correct date value `UTCDateTime(strtotime($_POST['startdate'] . " 00:00:00")*1000)` – Neil Lunn May 19 '18 at 03:53

0 Answers0