0

I am having an issue with mongodb. Could anyone explain me why this works (gives back some results):

db.getCollection('test').find({"reportedOn" : { "$gte" :    ISODate("2019-03-01T01:20:00"), "$lt" : ISODate("2019-04-01T02:00:00") } });

And this doesn't work (returns zero):

db.getCollection('test').find({"reportedOn" : { "$gte" : { "$date" : 1551398400000 }, "$lt" : { "$date" : 1554073200000 } } });

Thanks a lot.

aMJay
  • 2,215
  • 6
  • 22
  • 34

2 Answers2

1

You may have to check this kind of related topic to understand why you actually can't use an epoch time directly in your query.

Here is the interesting part of querying on Date :

According to Data Types in the mongo Shell both should be equivalent:

The mongo db provides various methods to return the date, either as a string or as a Date object:

  • Date() method which returns the current date as a string.
  • new Date() constructor which returns a Date object using the ISODate() wrapper.
  • ISODate() constructor which returns a Date object using the ISODate() wrapper.

and using ISODate should still return a Date object.

{"$date": "ISO-8601 string"} can be used when strict JSON representation is required.

So you may want to check all ISO-8601 available formats and update your code accordingly to the expected format in order to get this working as expected.

Sense
  • 1,096
  • 8
  • 20
0

Try the following query

{ "$date" : { "$numberLong" : "<dateAsMilliseconds>" } }

as mentioned in the MongoDB docs instead of comparing with $date only. Link

Shivam Pandey
  • 3,756
  • 2
  • 19
  • 26