$dateAdd
Adds a specified number of time units to a date. It's useful in scenarios where you need to calculate future dates based on a given date and a time interval.
Syntax
$dateAdd: { startDate: <expression>, unit: <string>, amount: <number>, timezone: <string> }
Parameters
startDate
objectrequiredThe starting date for the addition operation.
unit
stringrequiredThe unit of time to add. Valid units include year, quarter, month, week, day, hour, minute, second, millisecond.
amount
numberrequiredThe number of units to add.
timezone
stringOptional. The timezone to use for the operation.
Examples
Adding days to a date
This query projects eventName and computes a newEndDate by adding 7 days to a date constructed from nested year, month, and day fields.
Query:
db.stores.aggregate([
{ $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" } },
{ $unwind: "$promotionEvents" },
{ $unwind: "$promotionEvents.promotionalDates" },
{
$project: {
eventName: 1,
newEndDate: {
$dateAdd: {
startDate: {
$dateFromParts: {
year: "$promotionEvents.promotionalDates.endDate.Year",
month: "$promotionEvents.promotionalDates.endDate.Month",
day: "$promotionEvents.promotionalDates.endDate.Day"
}
},
unit: "day",
amount: 7
}
}
}
}
])
Output:
[
{
"_id": "e6410bb3-843d-4fa6-8c70-7472925f6d0a",
"newEndDate": "2024-10-06T00:00:00.000Z"
}
]
Adding months to a date
This aggregation query projects the eventName and calculates a newStartDate by adding 1 month to a reconstructed start date from nested promotion fields.
Query:
db.stores.aggregate([
{ $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" } },
{ $unwind: "$promotionEvents" },
{ $unwind: "$promotionEvents.promotionalDates" },
{
$project: {
eventName: "$promotionEvents.eventName",
newStartDate: {
$dateAdd: {
startDate: {
$dateFromParts: {
year: "$promotionEvents.promotionalDates.startDate.Year",
month: "$promotionEvents.promotionalDates.startDate.Month",
day: "$promotionEvents.promotionalDates.startDate.Day"
}
},
unit: "month",
amount: 1
}
}
}
}
])
Output:
[
{
"_id": "e6410bb3-843d-4fa6-8c70-7472925f6d0a",
"eventName": "Massive Markdown Mania",
"newStartDate": "2024-10-21T00:00:00.000Z"
}
]