$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.

CategoryDate
MongoDB Version5.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $dateSubtract: { startDate: <date-expression>, unit: <unit>, amount: <number>, timezone: <timezone> } }

⚙️ Parameters

startDateThe date to subtract from; a Date, timestamp, or date expression.
unitThe unit: year, month, week, day, hour, minute, second, or millisecond.
amountThe amount to subtract; positive subtracts, negative adds; out of int64 range throws.
timezoneOptional 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏