Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 986
kschaeffler Avatar asked Nov 15 '11 12:11

kschaeffler


People also ask

How do I get the difference between two dates in MongoDB?

The $dateDiff expression returns the integer difference between the startDate and endDate measured in the specified units . Durations are measured by counting the number of times a unit boundary is passed. For example, two dates that are 18 months apart would return 1 year difference instead of 1.5 years .

What is ISODate in MongoDB?

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.

What is $GTE in MongoDB?

$gte selects the documents where the value of the field is greater than or equal to (i.e. >= ) a specified value (e.g. value .) For most data types, comparison operators only perform comparisons on fields where the BSON type matches the query value's type.

How is datetime stored in MongoDB?

MongoDB will store date and time information using UTC internally, but can easily convert to other timezones at time of retrieval as needed. Because this is mainly implemented to help coordinate internal processes like replication and sharding, you should probably not use this in your own application's logic.


1 Answers

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/ 
like image 174
DrColossos Avatar answered Sep 21 '22 03:09

DrColossos