1

I need to query the data between two dates. I was pushing data into mongo where dates are in the format : 13-10-2015 15:08:22

Is there a way to do it?

Can't i tell mongo to compare these as dates with format explicilty mentioned

Sudhanshu Gupta
  • 2,255
  • 3
  • 36
  • 74
  • If you are using shell you should write dates in ISODate format. – Erkan Demirel Jan 12 '16 at 12:30
  • This is a string which i am sending to the mongo .... This is not in ISO format – Sudhanshu Gupta Jan 12 '16 at 12:39
  • 1
    But Mongo keeps date on ISO format so it will not understand your string. – Erkan Demirel Jan 12 '16 at 13:05
  • Storing your dates in ISODate gives you an edge over strings since ISODate is just a helper function that wraps a JavaScript date object and you can thus call methods on (such as `getMonth()`) while also being able to easily eye ball its value.Using a string for the date means you'd be parsing strings all the time when you have to work with your dates, so it's advisable to convert your string formatted dates into ISODate objects which will make it easier for you to query date ranges. This [question](http://stackoverflow.com/questions/2900674/) has some guidelines on how to do the conversion. – chridam Jan 12 '16 at 13:49

3 Answers3

5

You can use the generic $gte and $lte query modifiers when dealing with Dates in mongo

{ $gte: startDate, $lte: endDate }

should work just fine (where endDate and startDate are Javascript Date objects)

SlashmanX
  • 2,489
  • 18
  • 16
1

You can use aggregate function in mongodb.

You can get dates using this :

let todayDate = new Date();
let beforeDate = new Date();
beforeDate.setDate(beforeDate.getDate() - 15);

[Here 15 is days. It will subtract 15 days from current date].

TableName.aggregate([
        {
            "$match":
                {
                    "Date":
                        {
                            "$lte": todayDate,
                            "$gte": beforeDate
                        }
                }
        }
    ]) 
sohamdodia
  • 357
  • 1
  • 4
  • 11
0
let today = new Date();
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
{
$match: {
    createdAt: {
      $gte: sevenDaysAgo,
       $lte: today,
     },
  },
},