Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date comparison in mongodb

Tags:

date

mongodb

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.

like image 431
maggs Avatar asked Jun 26 '15 11:06

maggs


People also ask

How do I compare two dates in MongoDB?

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.

What is $date in MongoDB?

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 .


2 Answers

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/

like image 124
L_7337 Avatar answered Oct 09 '22 04:10

L_7337


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')}}) 
like image 40
Aljohn Yamaro Avatar answered Oct 09 '22 06:10

Aljohn Yamaro