The $subtract operator subtracts one value from another in MongoDB aggregation pipelines. Use it for budget balances, inventory variance, date durations, and any calculation where you need a minus b.
01
Subtraction
First minus second.
02
Syntax
[ a, b ] array.
03
Numbers
Fields & literals.
04
Dates
Millis difference.
05
Use Cases
Balance, variance.
06
vs $add
Minus vs sum.
Fundamentals
Definition and Usage
In MongoDB’s aggregation framework, the $subtract operator computes expression1 − expression2. For example, { $subtract: [ 10, 3 ] } returns 7, and { $subtract: [ "$budget", "$spent" ] } returns how much budget remains.
When both operands are dates, the result is the difference in milliseconds. Combine with $divide to express duration in days or hours. Pair with $abs when you need the magnitude of a difference regardless of sign.
💡
Beginner Tip
Order matters: { $subtract: [ "$actual", "$expected" ] } gives a positive value when actual exceeds expected. Swap the operands if you need the opposite sign.
Foundation
📝 Syntax
The $subtract operator takes an array of two expressions:
mongosh
{ $subtract: [ <expression1>, <expression2> ] }
Literal Examples
mongosh
{ $subtract: [ 10, 3 ] }
// Result: 7
{ $subtract: [ "$total", "$discount" ] }
// total minus discount
{ $subtract: [ "$endDate", "$startDate" ] }
// Date difference in milliseconds
Syntax Rules
First argument — value to subtract from (minuend).
Second argument — value to subtract (subtrahend).
Result — expression1 − expression2.
Numbers — standard arithmetic subtraction.
Dates — returns milliseconds between the two dates.
Use inside $project, $addFields, $set, or nested expressions.
null in either operand — returns null.
💡 $subtract vs $add
$subtract — exactly two operands: a - b
$add — sums two or more values: a + b + c
Subtract three values: { $subtract: [ a, { $add: [ b, c ] } ] }
Cheat Sheet
⚡ Quick Reference
Question
Answer
Operator type
Aggregation expression operator (arithmetic)
Syntax
{ $subtract: [ a, b ] }
Operands
Exactly two expressions
Date result
Milliseconds (number)
Days from dates
$divide: [ { $subtract: [...] }, 86400000 ]
Common stages
$project, $addFields, $set
Literal
{
$subtract: [ 100, 25 ]
}
Returns 75
Fields
{
$subtract: ["$a", "$b"]
}
Field difference
+ $abs
$abs: {
$subtract: [...]
}
Absolute diff
Dates
$subtract: [
"$end", "$start"
]
Millis apart
Hands-On
Examples Gallery
Compute budget remainders, inventory variance, date durations, and absolute differences with $subtract.
📚 Basic Subtraction
Start with a budgets collection and compute remaining amounts.
Sample Input Documents
Suppose you have a budgets collection tracking planned vs actual spending:
$subtract accepts only two operands. Nest calls or use $add with negative values for longer expressions.
Bonus — Literal Subtraction
Subtract fixed amounts or compute characters remaining:
mongosh
db.posts.aggregate([
{
$project: {
title: 1,
charsRemaining: {
$subtract: [
280,
{ $strLenCP: "$body" }
]
}
}
}
])
// 280 - body length = characters left before limit
How It Works
Mix literals with field expressions. Negative results mean the text exceeds the limit.
Applications
🚀 Use Cases
Budget tracking — compute remaining funds as budget minus spent.
Inventory variance — compare expected vs actual stock levels.
Date durations — measure project length, subscription age, or time between events.
Net calculations — derive final amounts after discounts, fees, or deductions.
🧠 How $subtract Works
1
MongoDB evaluates both operands
Each expression resolves to a number, date, or nested result from field paths or literals.
Input
2
The second value is subtracted from the first
For numbers: standard arithmetic. For dates: millisecond difference.
Compute
3
The result is stored in the pipeline
The difference is written to the field you define in $project or $addFields.
Output
=
−
Numeric or time difference
Chain with $abs, $divide, or $cond as needed.
Wrap Up
Conclusion
The $subtract operator is a fundamental arithmetic tool in MongoDB aggregation pipelines. It computes the difference between two numbers or the millisecond span between two dates, enabling budget tracking, variance analysis, and duration calculations.
Remember operand order: first minus second. Next in the series: $switch.
Pay attention to operand order — [ a, b ] means a - b
Use $abs when only the magnitude of a difference matters
Divide date differences by 86,400,000 for days
Use $ifNull when missing fields should count as zero
Nest $subtract or use $add for multi-value expressions
❌ Don’t
Pass more than two operands directly — $subtract takes exactly two
Subtract incompatible types (e.g., number minus string)
Forget that date results are in milliseconds, not days
Assume null operands become zero — they return null
Confuse $subtract with the query $inc update operator
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $subtract
Use these points when writing arithmetic in MongoDB pipelines.
5
Core concepts
−01
a − b
Two operands.
Purpose
📝02
[ expr1, expr2 ]
Array syntax.
Syntax
📅03
Dates
Millis diff.
Dates
🛠04
+ $abs
Variance.
Pattern
⚠05
Order matters
First minus second.
Rule
❓ Frequently Asked Questions
$subtract returns the difference of two expressions: the first minus the second. For numbers, { $subtract: [ 10, 3 ] } returns 7. It is an aggregation expression operator used inside stages like $project and $addFields.
The syntax is { $subtract: [ <expression1>, <expression2> ] }. The result is expression1 minus expression2. Both can be field references, literals, or nested expressions.
Yes. When both expressions are dates, $subtract returns the difference in milliseconds. Divide by 86,400,000 to convert to days, or use $divide for custom units.
$subtract computes a - b with two operands. $add sums multiple values. To subtract several numbers, nest $subtract calls or add negative values with $add.
If either operand is null, $subtract returns null. Use $ifNull on fields when missing values should be treated as zero.