$dateSubtract (Subtract from a Date)
Last updated: 2026-10-09
$dateSubtract (Subtract from a Date)
$dateSubtract subtracts a specified amount of a time unit from a date and returns the new date — the mirror of $dateAdd. Great for membership expiry, coupon start dates, or retention windows. unit supports year, month, week, day, hour, minute, second, and millisecond; negative amount equals adding. timezone is optional and defines the calendar used. Like $dateAdd it works in $project, $set and other stages; null/missing date yields null.
| Category | Date |
|---|---|
| MongoDB Version | 5.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $dateSubtract: { startDate: <date-expression>, unit: <unit>, amount: <number>, timezone: <timezone> } }
⚙️ Parameters
| startDate | The date to subtract from; a Date, timestamp, or date expression. |
|---|---|
| unit | The unit: year, month, week, day, hour, minute, second, or millisecond. |
| amount | The amount to subtract; positive subtracts, negative adds; out of int64 range throws. |
| timezone | Optional timezone for the calculation. |
Returns:The new date (BSON Date); null if startDate is null or missing.
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $dateSubtract: remind 3 days before due date (UTC+8)
db.orders.aggregate([
{ $project: {
remindAt: { $dateSubtract: { startDate: '$dueDate', unit: 'day', amount: 3, timezone: '+08:00' } }
} }
])
Output:
{ "_id": 1, "remindAt": ISODate("2026-10-22T00:00:00Z") }
{ "_id": 2, "remindAt": ISODate("2026-11-12T00:00:00Z") }
📌 Notes
- Identical parameters to $dateAdd, opposite direction
- Month arithmetic also truncates to the result month's days
- Results may predate 1970; BSON Date supports negative timestamps
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QHow do $dateSubtract and $dateAdd relate?
ASame parameters, opposite direction; negative amounts make them equivalent.
QCan the result predate 1970?
AYes — BSON Date supports negative timestamps before 1970.
QWhat is the difference from $dateDiff?
A$dateSubtract returns a new date; $dateDiff returns an integer difference.