42

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.

Anju
  • 631
  • 2
  • 9
  • 25
maggs
  • 763
  • 2
  • 9
  • 15

3 Answers3

50

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/

L_7337
  • 2,650
  • 28
  • 42
21

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')}})
Prayag k
  • 647
  • 9
  • 23
Aljohn Yamaro
  • 2,629
  • 25
  • 22
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")
Abdul Rahman A Samad
  • 1,062
  • 1
  • 15
  • 21