b0bu
b0bu

Reputation: 1250

Mongodb Date() returning the wrong value

from the mongodb shell, I'm having an issue with a date query. This is a test database and the problem is better explained by example:

Example field in a collection

"createdOn" : ISODate("2015-11-23T00:49:01.800Z")

When I enter a date of this month for testing at the shell such as:

new Date(2015, 11, 23)
ISODate("2015-12-23T05:00:00Z")

You can see it's a month a head, meaning It's messing my queries. Where I have to drop back a month in order to get what I need for this month:

db.collection.find({'createdOn': {'$lte': new Date(2015, 10, 23)}}).count()
306
db.collection.find({'createdOn': {'$gte': new Date(2015, 10, 23)}}).count()
10

All entries above were created in Nov, but when using the correct month:

db.collection.find({'createdOn': {'$gte': new Date(2015, 11, 23)}}).count()
0

How does this even happen?

Upvotes: 1

Views: 1846

Answers (2)

Sarath Nair
Sarath Nair

Reputation: 2868

What you are doing is almost right but you have missed on a point that:

Javascript counts month from 0 to 11 instead of 1 to 12

January is 0. December is 11. So to see for entries created in november you have to apply query like:

db.collection.find({'createdOn': {'$gte': new Date(2015, 10, 23)}})

Upvotes: 2

EmmaZhao
EmmaZhao

Reputation: 111

You should use Date like this: new Date("2015-11-23"). See Mongo Reference

Upvotes: 3

Related Questions