$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.
| Category | Math |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $subtract: [ <expression1>, <expression2> ] }
⚙️ Parameters
| minuend | A numeric value, a date, or an expression resolving to either. |
|---|---|
| subtrahend | A 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
- Accepts exactly two arguments; more than two throws
- Date minus date returns milliseconds; divide by 86400000 to get days
- Any null or missing argument yields null
🏷️ Related Tags
💡 Related Cases
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.