Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB date comparison

How MongoDB performs date comparison? I tried a few test on the MongoDB shell:

> db.test.insert( { "dates" : [ new Date("Jul 21, 1983"), new Date("Aug 7, 1999") ] } )
"ok"
> db.test.find()

[ 
  {   "_id" : {   "$oid" : "5201e8b7cc93742c160bb9d8"   },   "dates" : [   "Thu Jul 21 1983 00:00:00 GMT+0200 (CEST)",   "Sat Aug 07 1999 00:00:00 GMT+0200 (CEST)" ]   }
]

Now I'll try to get all objects with a date in dates greater than Aug 30, 2000.

> db.test.find( { "dates" : { $gt : new Date("Aug 30, 2000") } } )

[

]

As expected, the document doesn't match. Using "Aug 30, 1999", instead...

> db.test.find( { dates : { $gt : new Date("Aug 30, 1999") } } )

[ 
  {   "_id" : {   "$oid" : "5201e8b7cc93742c160bb9d8"   },   "dates" : [   "Thu Jul 21 1983 00:00:00 GMT+0200 (CEST)",   "Sat Aug 07 1999 00:00:00 GMT+0200 (CEST)" ]   }
]

The document matches! What am I missing?

like image 648
Giovanni Lovato Avatar asked Aug 07 '13 06:08

Giovanni Lovato


People also ask

How does MongoDB compare date time?

Comparison Based on Date in MongoDB First, create a collection called 'data' using the document to further understand the concept. Use the find() function to show all the documents in a collection. The following is the date-based return query. Records with a creation date after 2018-05-19T11:10:23Z will be returned.

How does MongoDB select date?

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.

Does MongoDB have a date type?

The recommended way to store dates in MongoDB is to use the BSON Date data type. The BSON Specification refers to the Date type as the UTC datetime and is a 64-bit integer. It represents the number of milliseconds since the Unix epoch, which was 00:00:00 UTC on 1 January 1970.


1 Answers

It seems to be related to the date conversion.

What version of MongoDB are you using? In the online shell of MongoDB I get the following:

> new Date("Jul 21, 1983")
"Thu Jul 21 1983 00:00:00 GMT+0200 (CEST)"
> new Date("Aug 7, 1999")
"Sat Aug 07 1999 00:00:00 GMT+0200 (CEST)"

> new Date("Aug 30, 2000")
"Wed Aug 30 2000 00:00:00 GMT+0200 (CEST)"
> new Date("Aug 30, 1999")
"Mon Aug 30 1999 00:00:00 GMT+0200 (CEST)"

However, if I try in MongoDB 2.2.2

> new Date("Jul 21, 1983")
ISODate("1983-07-20T22:00:00Z")
> new Date("Aug 7, 1999")
ISODate("1999-08-06T22:00:00Z")
> new Date("Aug 30, 2000")
ISODate("2000-08-29T22:00:00Z")
> new Date("Aug 30, 1999")
ISODate("1999-08-29T22:00:00Z")

In your case, It seems that MongoDB is indexing the string version and then performing a basic string comparison which would explain the results your are getting.

like image 75
user1498724 Avatar answered Oct 18 '22 14:10

user1498724