47

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

I wrote the following query-

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

But the results doesn't fetches any record even though there are records for the dates upto 2015-06-24.

5
  • 1
    Your date is in string format. You need to save/update it in IOSDate format to get result from current query. Commented Jun 26, 2015 at 11:28
  • It is in date format only. Commented Jun 26, 2015 at 11:37
  • 8
    Try "$gte" : ISODate("2015-06-17 10:03:46.000Z") Commented Jun 26, 2015 at 11:38
  • It worked. Thanks. :) Can you please explain how and why did the earlier one didn't? Commented Jun 26, 2015 at 11:44
  • 2
    @L_7337 When you add a short explanation of the difference between Date and ISODate you could post this as an answer. Commented Jun 26, 2015 at 12:01

3 Answers 3

57

You can use ISODate to compare dates:

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

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

new Date() 

wraps the date in an ISODate helper, but is not able to convert in your query.

Check out this link for more information: https://www.mongodb.com/docs/v4.2/core/shell-types/

Sign up to request clarification or add additional context in comments.

3 Comments

Is there some reason that the Mongo shell allows queries with Date, since it doesn't seem to be useful in querying against Mongo date fields?
broken link, please update
Which library provides this ISODate function?
22

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')}}) 

Comments

18

You can use this:

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

It will convert your date format into this:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.