Reputation: 610
Let’s say I have a collection of subscriptions as below:
{
"id": "8SDQ8"
"durationInMonths": 12,
"startDate": {
"$date": "2020-07-03T09:14:46.609Z",
},
"endDate": {
"$date": "2021-07-03T09:14:46.609Z",
}
}
How can I add $durationInMonths to a variable date without being forced to fetch $durationInMonths beforehand (which adds an inefficient network round trip)? Something like this:
const myDate = new Date();
const sub = await Subscription.findOneAndUpdate({
id: '8SDQ8'
}, {
$set: {
startDate: myDate,
endDate: {
$addMonths(myDate, "$durationInMonths")
}
}
});
Upvotes: 1
Views: 183
Reputation: 706
Updated to calculate the end date in months:
db.Subscription.update(
{_id: "8SDQ8"
},
[
{ $set: {
startDate: myDate,
endDate: {$dateFromParts: {
'year' : { $year: myDate },
'month' : {$add: [
{ $month: myDate
},
"$duration"
]
},
'day': { $dayOfMonth: myDate
}
}
}
}
}
]
)
This answer assumes you only care about the year, month, and day, but you could easily include more precise date/time info in your endDate if you wanted to.
Upvotes: 1