'Get data between two dates mongo

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



Solution 1:[1]

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)

Solution 2:[2]

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

Solution 3:[3]

let today = new Date();
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
{
$match: {
    createdAt: {
      $gte: sevenDaysAgo,
       $lte: today,
     },
  },
},

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SlashmanX
Solution 2 sohamdodia
Solution 3 divya maddipudi