This question already has an answer here:
- Find objects between two dates MongoDB 11 answers
I'm using mongodb and I store datetime in my database in this way
for a date "17-11-2011 18:00" I store:
date = datetime.datetime(2011, 11, 17, 18, 0)
db.mydatabase.mycollection.insert({"date" : date})
I would like to do a request like that
month = 11
db.mydatabase.mycollection.find({"date.month" : month})
or
day = 17
db.mydatabase.mycollection.find({"date.day" : day})
anyone knows how to do this query?
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.
You can find record by month, day, year etc of dates by Date Aggregation Operators, like $dayOfYear, $dayOfWeek, $month, $year etc.
As an example if you want all the orders which are created in April 2016 you can use below query.
Here created is a date type field in documents, and $$ROOT we used to pass all other field to project in next stage, and give us all the detail of documents.
You can optimize above query as per your need, it is just to give an example. To know more about Date Aggregation Operators, visit the link.
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.You cannot straightly query mongodb collections by date components like day or month. But its possible by using the special $where javascript expression
or simply
(But i prefer the first one)
Check out the below shell commands to get the parts of date
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
If you want to search for documents that belong to a specific month, make sure to query like this:
Avoid quering like below as much as possible.
You can use MongoDB_DataObject wrapper to perform such query like below:
OR, similarly, using direct query string: