Anuj Mishra
Anuj Mishra

Reputation: 39

How to write a query in MongoDB to get data for last 7 days on rolling basis

I am trying to build a MongoDB query to get last 7 days data on rolling basis. Can you help me how to write query to fetch data on dynamic dates.

Upvotes: 1

Views: 4006

Answers (3)

Tony S
Tony S

Reputation: 571

To get last 7 days datas :

let lastWeek = new Date();
lastWeek.setDate(lastWeek.getDate() -7);
db.yourtable.find({ "yourelement": { $gte: lastWeek}} );

Is this what you want to do?

Upvotes: 0

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59513

For any Date operation in MongoDB I recommend the moments.js library:

db.collectioName.find({ "dateField": { $gte: moment().subtract(7, 'days').toDate() } })

If you like to get data older than "last midnight minus 7 days" then you would use

db.collectioName.find(
   { "dateField": { $gte: moment().startOf('day').subtract(7, 'days').toDate() } }
) 

Upvotes: 0

Dylan
Dylan

Reputation: 2219

db.getCollection('collectioName').find({"dateField":{  $lt: new Date(), 
    $gte: new Date(new Date().setDate(new Date().getDate()-7))}})

Swap out the collectioName and dateField with what you have and it should work for ya!

Upvotes: 2

Related Questions