$dateSubtract
Subtracts a specified time unit from a date. It's useful for calculating past dates or intervals in aggregation pipelines.
Syntax
$dateSubtract: { startDate: <dateExpression>, unit: <unit>, amount: <number>, timezone: <timezone> }
Parameters
startDate
objectrequiredThe date expression to subtract from.
unit
stringrequiredThe time unit to subtract (for example, "day", "hour").
amount
numberrequiredThe amount of the time unit to subtract.
timezone
stringOptional. Timezone for date calculation.
Examples
Subtract seven days
This query calculates the date one week before the lastUpdated field. This query uses $dateSubtract to calculate the date exactly seven days before the storeOpeningDate timestamp.
Query:
db.stores.aggregate([
{
$match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" }
},
{
$project: {
_id: 0,
dateOneWeekAgo: {
$dateSubtract: {
startDate: "$storeOpeningDate",
unit: "day",
amount: 7
}
}
}
}
])
Output:
[
{
"dateOneWeekAgo": "2024-08-29T11:50:06.549Z"
}
]