Date query with ISODate in mongodb doesn't seem to work
Although $date
is a part of MongoDB Extended JSON and that's what you get as default with mongoexport
, I don't think you can really use it as a part of the query.
If try exact search with $date
like below:
db.foo.find({dt: {"$date": "2012-01-01T15:00:00.000Z"}})
you'll get the error:
error: { "$err" : "invalid operator: $date", "code" : 10068 }
Try this:
db.mycollection.find({
"dt" : {"$gte": new Date("2013-10-01T00:00:00.000Z")}
})
or (following comments by @user3805045):
db.mycollection.find({
"dt" : {"$gte": ISODate("2013-10-01T00:00:00.000Z")}
})
ISODate
may be also required to compare dates without time (noted by @MattMolnar).
According to Data Types in the mongo Shell both should be equivalent:
The mongo shell provides various methods to return the date, either as a string or as a Date object:
- Date() method which returns the current date as a string.
- new Date() constructor which returns a Date object using the ISODate() wrapper.
- ISODate() constructor which returns a Date object using the ISODate() wrapper.
and using ISODate
should still return a Date object.
{"$date": "ISO-8601 string"}
can be used when strict JSON representation is required. One possible example is Hadoop connector.
From the MongoDB cookbook page comments:
"dt" :
{
"$gte" : ISODate("2014-07-02T00:00:00Z"),
"$lt" : ISODate("2014-07-03T00:00:00Z")
}
This worked for me. In full context, the following command gets every record where the dt
date field has a date on 2013-10-01 (YYYY-MM-DD) Zulu:
db.mycollection.find({ "dt" : { "$gte" : ISODate("2013-10-01T00:00:00Z"), "$lt" : ISODate("2013-10-02T00:00:00Z") }})
Try this:
{ "dt" : { "$gte" : ISODate("2013-10-01") } }
I am using robomongo as the mongodb client gui and the below worked for me
db.collectionName.find({"columnWithDateTime" : {
$lt:new ISODate("2016-02-28T00:00:00.000Z")}})
On the app side I am using nodejs based driver mongodb(v1.4.3),the application uses datepicker in the ui which gives date like YYYY-mm-dd, this is then appended with default time like 00:00:00 and then given to the new Date()
constructor and then supplied to the mongodb criteria object,I think the driver converts the date to ISO date and the query then works and gives desired output, however the same new Date()
constructor does not work or show same output on robo mongo,for the same criteria,which is weird,since I used robomongo to cross check my criteria objects.
Whereas the default cli mongoshell works well with both ISODate
and new Date()
In json strict mode, you'll have to keep the order:
{
"dt": {
"$gte": {
"$date": "2013-10-01T00:00:00.000Z"
}
}
}
Only thing which worked to define my search queries on mlab.com.