Query Mongodb on month, day, year... of a datetime Query Mongodb on month, day, year... of a datetime python python

Query Mongodb on month, day, year... of a datetime


Dates are stored in their timestamp format. If you want everything that belongs to a specific month, query for the start and the end of the month.

var start = new Date(2010, 11, 1);var end = new Date(2010, 11, 30);db.posts.find({created_on: {$gte: start, $lt: end}});//taken from http://cookbook.mongodb.org/patterns/date_range/


You cannot straightly query mongodb collections by date components like day or month. But its possible by using the special $where javascript expression

db.mydatabase.mycollection.find({$where : function() { return this.date.getMonth() == 11} })

or simply

db.mydatabase.mycollection.find({$where : 'return this.date.getMonth() == 11'})

(But i prefer the first one)

Check out the below shell commands to get the parts of date

>date = ISODate("2011-09-25T10:12:34Z")> date.getYear()111> date.getMonth()8> date.getdate()25

EDIT:

Use $where only if you have no other choice. It comes with the performance problems. Please check out the below comments by @kamaradclimber and @dcrosta. I will let this post open so the other folks get the facts about it.

and check out the link $where Clauses and Functions in Queries for more info


how about storing the month in its own property since you need to query for it? less elegant than $where, but likely to perform better since it can be indexed.