MongoDB $subtract Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Math Operations

What You’ll Learn

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.

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.

📝 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 ] } ] }

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (arithmetic)
Syntax{ $subtract: [ a, b ] }
OperandsExactly two expressions
Date resultMilliseconds (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

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:

mongosh
[
  { "_id": 1, "department": "Marketing", "budget": 5000, "spent": 3200 },
  { "_id": 2, "department": "Engineering", "budget": 12000, "spent": 11500 },
  { "_id": 3, "department": "HR", "budget": 3000, "spent": 3500 }
]

Example 1 — Basic $subtract on Fields

Calculate how much budget remains:

mongosh
db.budgets.aggregate([
  {
    $project: {
      department: 1,
      budget: 1,
      spent: 1,
      remaining: {
        $subtract: [ "$budget", "$spent" ]
      }
    }
  }
])

How It Works

Each document gets a computed remaining field. Negative values mean spending exceeded the budget.

📈 Variance and Dates

Measure differences between expected and actual values, and compute time spans.

Example 2 — Inventory Variance with $abs

Find how far actual stock differs from expected, regardless of direction:

mongosh
db.inventory.aggregate([
  {
    $project: {
      item: 1,
      expected: 1,
      actual: 1,
      variance: {
        $abs: {
          $subtract: [ "$actual", "$expected" ]
        }
      }
    }
  }
])

// expected: 100, actual: 92  → variance: 8
// expected: 50,  actual: 58  → variance: 8

How It Works

$subtract gives a signed difference. Wrapping it in $abs returns the magnitude only — useful for QA and reporting.

Example 3 — Date Difference in Days

Subtract two date fields and convert milliseconds to days:

mongosh
db.projects.aggregate([
  {
    $project: {
      name: 1,
      startDate: 1,
      endDate: 1,
      durationDays: {
        $divide: [
          { $subtract: [ "$endDate", "$startDate" ] },
          86400000
        ]
      }
    }
  }
])

// 86400000 = milliseconds in one day (24 × 60 × 60 × 1000)

How It Works

Date subtraction returns milliseconds. Divide by 86,400,000 to get whole days, or use other divisors for hours or minutes.

Example 4 — Subtract Multiple Values

Subtract a discount and tax from a total using nested expressions:

mongosh
db.orders.aggregate([
  {
    $project: {
      orderId: 1,
      subtotal: 1,
      discount: 1,
      tax: 1,
      netAmount: {
        $subtract: [
          { $subtract: [ "$subtotal", "$discount" ] },
          "$tax"
        ]
      }
    }
  }
])

// subtotal: 100, discount: 10, tax: 5
// netAmount: 100 - 10 - 5 = 85

How It Works

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

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

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.

💡 Best Practices

✅ Do

  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about $subtract

Use these points when writing arithmetic in MongoDB pipelines.

5
Core concepts
📝 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.

Continue the Operator Series

Move on to $switch for multi-branch conditional logic, or review $abs for absolute differences.

Next: $switch →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful