I have a query where I need to get events that are one day before or after from a specific date. I need to add or subtract one day to that ISODate variable. Here is my query :
db.event.find().forEach( function (x) { print("x : " + x.EventID + ", " + x.ISODate); db.events.find( { "$or" : [{ "StartDate" : { "$gte" : x.ISODate } // Here i need to subtract one day }, { "EndDate": { "$lt" : x.ISODate} // Here i need to add one day }] }).forEach(function(otherDay) { print("x.EventID : " + x.EventID + ", other.Date : " + otherDay.StartDate + " - " + otherDay.EndDate); }); });
How can i add or subtract days to an ISODate variable in mongodb shell?
In MongoDB, you can use the $subtract aggregation pipeline operator to subtract numbers and/or dates. Specifically, $subtract can do the following three things: Subtract two numbers to return the difference. Subtract a number (in milliseconds) from a date and return the resulting date.
The $dateDiff expression returns the integer difference between the startDate and endDate measured in the specified units . Durations are measured by counting the number of times a unit boundary is passed. For example, two dates that are 18 months apart would return 1 year difference instead of 1.5 years .
MongoDB provides a variety of arithmetic expression operators. The $subtract operator is one of those operators. This operator is used to subtract two numbers or dates and returns the difference. If the argument is the two numbers, the result will come in a number.
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
Not an exact answer but related.
I needed to increment a date field for all items in my MongoDB collection in place, relative to the date value that was stored.
The query below will add 1 day to myDateField in myCollection.
db.myCollection.find().snapshot().forEach( function (elem) { const dateDiffInMs = 1 * 24 * 60 * 60000 db.myCollection.update( { _id: elem._id }, { $set: { myDateField: new Date(elem.myDateField.getTime() + dateDiffInMs) } } ); } );
1 day = 1 * 24 * 60 * 60000 = 1 x 24 hours x 60 minutes x 60 seconds x 1000 milliseconds
This has been answered on Query to get last X minutes data with Mongodb
query = { timestamp: { // 18 minutes ago (from now) $gt: new Date(ISODate().getTime() - 1000 * 60 * 18) } }
And in your case, for a number of days:
"StartDate" : { "$gte" : new Date(ISODate().getTime() - 1000 * 3600 * 24 * 3) }
or
"StartDate" : { "$gte" : new Date(ISODate().getTime() - 1000 * 86400 * 3) }
(here the 3 is your number of days)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With