$subtract (Subtraction)

Last updated: 2026-10-09

$subtract (Subtraction)

$subtract performs subtraction in aggregation expressions, the counterpart of $add. It takes exactly two arguments: number minus number returns the difference, date minus date returns milliseconds, and date minus milliseconds returns an earlier date. It is often used in $project or $set to compute differences such as a discounted price or the elapsed time between two timestamps. Note that $subtract accepts only two arguments and cannot take several operands the way $add does. Any null or missing argument yields null.

CategoryMath
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $subtract: [ <expression1>, <expression2> ] }

⚙️ Parameters

minuendA numeric value, a date, or an expression resolving to either.
subtrahendA number (milliseconds) or a date expression to subtract from the minuend.

Returns:The numeric difference; date minus date returns milliseconds; date minus milliseconds returns a date

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $subtract: compute price after discount
db.orders.aggregate([
  { $project: {
      finalPrice: { $subtract: ['$price', '$discount'] }
  } }
])

Output:

{ '_id': 1, 'finalPrice': 90 }
{ '_id': 2, 'finalPrice': 45 }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QCan $subtract compute the day difference between two dates?
AIt returns milliseconds; divide by 86400000 for days, or use $dateDiff with the day unit.
QHow are $subtract and $add related?
AThey are inverses; $subtract takes two arguments while $add accepts several.
QWhat does a date minus milliseconds give?
AAn earlier date; for example, subtracting 86400000 from an order date gives the previous day.
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%

🙏 帮我们做得更好

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

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