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
.
Comparison Based on Date in MongoDB First, create a collection called 'data' using the document to further understand the concept. Use the find() function to show all the documents in a collection. The following is the date-based return query. Records with a creation date after 2018-05-19T11:10:23Z will be returned.
Date() returns the current date as a string in mongosh . new Date() returns the current date as a Date object. mongosh wraps the Date object with the ISODate helper. The ISODate is in UTC .
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: http://docs.mongodb.org/manual/core/shell-types/
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')}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With