I'm trying to get the next Tuesday (day 2 of ISO Week) from today on. I have the current date from the global var "$$NOW"
and the current day of ISO Week by the following operator: { $dayOfWeek: "$$NOW" }
. But I can't think of any way to get the date of the next Tuesday in MongoDB-Aggregation.
For example i have as Input:
"$$NOW" which is => new Date("2021-09-13T16:20:00Z") // Today Monday
And now I want to get the next Tuesday:
new Date("2021-09-14T16:20:00Z") // coming Tuesday
which is quite easy, but if there is a week shift, it gets a bit more difficult. If the NOW date would be:
"$$NOW" which is => new Date("2021-09-16T16:20:00Z") // coming Thursday would be Today
the next Tuesday would be the:
new Date("2021-09-21T16:20:00Z") // Tuesday next week
So I always want to get the next following Tuesday after Today.
At the end, I want to create a mongo pipeline like this:
[{
$addFields: {
"nextTuesday": new Date(" the date of the next Tuesday ")
}
}]
I would be very happy about any help!
CodePudding user response:
MongoDB has the $dayOfWeek operator that returns 1 for Sunday, 7 for Saturday.
On that scale, the formula to find a desired day of the week would be:
(((desired_day 6) - current_day) modulo 7) 1
Which in the MongoDB aggregation language, would look like:
{$addFields:{
nextTuesday:{
$toDate:{
$add:[
"$$NOW",
{$multiply:[
86400000,
{$add:[
1,
{$mod:[
{$subtract:[
9,
{$dayOfWeek:"$$NOW"}
]},
7
]}
]}
]}
]
}
}
}}