Query date range of the same day

Hello,

on my node.js server I get a date range like the following…

{
  begin: 'Mon Feb 07 2022 00:00:00 GMT 0200 (Israel Standard Time)',
  end: 'Mon Feb 07 2022 00:00:00 GMT 0200 (Israel Standard Time)'
}

using

new Date(req.query.begin)
new Date(req.query.end)

I get the following…

 2022-02-07T00:00:00.000Z // same day
 2022-02-07T00:00:00.000Z

this is how I query the database

Model.aggregate([
     'dateCreated': {
          '$gte': begin,
          '$lte': end
      }
])
...

it is not working until I change the date range for the following…

 2022-02-06T00:00:00.000Z // 1 day difference
 2022-02-07T00:00:00.000Z

my question is, why using date range of the same day is not working?

please help me understand.

thank you!

The only dateCreated that will match gte:day and lte:day are dateCreated that are both gte and lte so that only dateCreated exactly equal to the date value.

Try
gte:2022-02-07T00:00:00.000Z
lte:2022-02-07T23:59:59:999Z

1 Like

To expand a bit on the answer, the dates are stored as full date-time value. Think of it as ISODate("2022-02-07T00:00:00.000Z") is storing February 7th 2022 at midnight. Comparing ISODate("2022-02-07T00:00:00.000Z") and ISODate("2022-02-07T01:00:00.000Z") will not show them as equal since the full “datetime” is being compared.

You could truncate the value to just date (as string) and do equality comparison but that will not be able to use indexes the way using stored datetime with range comparison can.

Asya

2 Likes