Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (47.6k points)

I don't seem to be able to get even the most basic date query to work in MongoDB. With a document that looks something like this:

     "_id" : "foobar/201310", 

     "ap" : "foobar", 

     "dt" : ISODate("2013-10-01T00:00:00.000Z"), 

     "tl" : 375439 

}

And a query that looks like this:

   "dt" : { 

      "$gte" : { 

         "$date" : "2013-10-01T00:00:00.000Z" 

       } 

   } 

}

I get 0 results from executing:

db.mycollection.find({ 

"dt" : { "$gte" : { "$date" : "2013-10-01T00:00:00.000Z"}}

})

Any ideas why this doesn't work?

For reference, this query is being produced by Spring's MongoTemplate so I don't have direct control over the query that is ultimately sent to MongoDB.

(P.S.)

> db.version() 

2.4.7

Thanks!

2 Answers

0 votes
by (106k points)

If date query with ISODate in MongoDB doesn't seem to work you should try this:

{ "dt" : { "$gte" : ISODate("2013-10-01") } }

0 votes
by (108k points)

$date is a part of MongoDB Extended JSON and that is considered to be as default with mongoexport I don't think you can really use it as a part of the query. Try this:

db.mycollection.find({

    "dt" : {"$gte": new Date("2013-10-01T00:00:00.000Z")}

})

The mongo shell have various methods to return the date, either as a string or as a Date object:

  1. Date() method is used to returns the current date as a string.

  2. new Date() constructor which is used to returns a Date object using the ISODate() wrapper.

  3. ISODate() constructor is used to returns a Date object using the ISODate() wrapper.

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
2 answers
asked Sep 9, 2019 in SQL by Sammy (47.6k points)
+2 votes
1 answer
0 votes
1 answer

Browse Categories

...