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
No comments for this post

Required. 30 chars of fewer.

Required.

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