Date Queries in MongoDB

Far too many times have I wanted to do a query on a date in MongoDB, only to find there is literally no documentation on it. So, in order that I shall not forget for next time, I thought I’d post it here.

I’m sure there are probably other methods, but here is one using the $where expression. The $where expression is pretty awesome, it lets you evaluate an arbitrary JavaScript expression, where this is populated with the current document being checked. So, we just compare it to a JavaScript date object.

db.collection.find({$where: "this.date_field > new Date(2009, 11, 02)"})

Now I shall never forget again :)

Comments

Make comment

Nice tip, thanks for the post. I was also finding the MongoDB documentation lacking when it comes to using dates.

Note that the JavaScript “new Date” constructor uses a zero-based month number. So in this example, the search is filtering for dates greater than December 2, 2009 _not_ November 2, 2009. To see for yourself, enter the command at the MongoDB console:

> new Date(2009, 11, 02)

Wed Dec 02 2009 00:00:00 GMT-0800 (PST)”

Indeed, very good point about javascript date weirdness.

I tend to just do Date(‘DD/MM/YYYY’) as a string these days, and it saves a lot of confusion.

It works but will it take use of the indexes??

The where clause would evaluate each document with this expression;

This is true, I’m guessing no indexing would be taken into account here.

In pymongo, I’d just pass the datetime object and everything would be fine, but for the shell I couldn’t find any way to do it, hence this not too great method.

I guess I could look into the pymongo source to find out how they do it, which I’m guessing is the “proper” way.

Required. 30 chars of fewer.

Required.

captcha image Please, enter symbols, which you see on the image