Greg
Greg

Reputation: 2609

Mongo date query fails on edge cases

I'm puzzled by the lack of accuracy for date ranges around edge cases. I have documents whose dates always start at the very beginning of a day - hr/min/sec of 00:00:00 - and am unable to query them using the $gte operator.

> db.days.find({dateR : {$gte:new Date(2013,9,14)}},{dateR:1})
null

> db.days.find({dateR : {$gte:new Date(2013,9,13)}},{dateR:1})
{ "_id" : ObjectId("525b79b5c598c6f439000600"), "dateR" : ISODate("2013-10-14T00:00:00Z") }

Why doesn't the document found in the second query appear for the first query?

Upvotes: 0

Views: 136

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311945

This is happening because new Date(2013,9,14) creates the date in terms of the local time zone, but MongoDB dates are always UTC.

This should work:

db.days.find({dateR: {$gte: new Date(Date.UTC(2013, 9, 14))}}, {dateR: 1})

Upvotes: 2

Related Questions