Reputation: 39
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
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
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
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