Date comparison in mongodb

I want to receive all documents after a certain date. My database has date as -DateAdded:"2014-12-17 10:03:46.000Z"

I wrote the following request -

db.collection.find({DateAdded:{"$lte":new Date("2015-06-17 10:03:46.000Z")}})

      

But the results do not retrieve any record, even if there are records for dates before 2015-06-24

.

+3


source to share


4 answers


You can use ISODate to compare dates:

"$lte" : ISODate("2015-06-17T10:03:46Z")

      

ISODate works because that's the format your date is in.



new Date() 

      

validates the date in the ISODate helper, but cannot convert to your request.

Check out this link for more information: http://docs.mongodb.org/manual/core/shell-types/

+7


source


Use ISODate



format: {'field': {$operator: ISODate(yyyy-MM-ddThh:mm:ss.msZ)}}

example: db.getCollection('yourCollection').find({'sampleField': {$lte: ISODate('2015-06-17T10:03:46.000Z')}})

      

+1


source


You can use this:

db.collection.find({DateAdded:{"$lte":new Date("2017-11-01")}})

      

It will convert your date format to this:

ISODate("2017-11-01T00:00:00Z")

      

0


source


Make sure your date in mongodb is of type Date. Then the ISO date conversion should be done automatically by mongo. eg

Task.find({ date: { $gt: "2018-01-30T16:08:53.758Z", $lte: "2018-02-01T02:08:53.770Z" }})

      

check this post stack question

-1


source







All Articles