MongoDB/Mongoose querying at a specific date?

Unitech picture Unitech · Aug 15, 2012 · Viewed 190.3k times · Source

Is it possible to query for a specific date ?

I found in the mongo Cookbook that we can do it for a range Querying for a Date Range Like that :

db.posts.find({"created_on": {"$gte": start, "$lt": end}})

But is it possible for a specific date ? This doesn't work :

db.posts.find({"created_on": new Date(2012, 7, 14) })

Answer

rdrey picture rdrey · Aug 15, 2012

That should work if the dates you saved in the DB are without time (just year, month, day).

Chances are that the dates you saved were new Date(), which includes the time components. To query those times you need to create a date range that includes all moments in a day.

db.posts.find( //query today up to tonight
  {"created_on": {"$gte": new Date(2012, 7, 14), "$lt": new Date(2012, 7, 15)}})