MongoDB $subtract Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $subtract?

$subtract is a MongoDB aggregation expression that returns expression1 minus expression2. Use it for numbers, for the millisecond difference between two dates, or to subtract milliseconds from a date.

Remember
$subtract = a − b for aggregation

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

10 − 3 → 7
date − date → milliseconds
date − number → earlier date (number = ms)

null / missing operand → null
exactly two arguments (not a list of many)
UsePrefer
a − b (two values)$subtract
Sum many values$add
Calendar units (days, months)$dateDiff / $dateSubtract
Multiply / divide$multiply / $divide

How to Use $subtract in MongoDB

Put the value you keep first, then the value you remove.

  1. Choose an expression stage ($addFields or $project).
  2. Pass two expressions: result = first − second.
  3. For a total like price + fee − discount, nest $add inside $subtract.
  4. For dates: date − date → ms; date − ms → date (date must be first).
PieceRequired?Role
Expression 1YesMinuend (starting value / date)
Expression 2YesSubtrahend (amount or date to remove)
$ifNullNoDefault missing numbers to 0

Pseudocode

Pseudocode
for each document:
    a = evaluate(expression1)
    b = evaluate(expression2)
    if a is null or b is null:
        result = null
    else:
        result = a − b   // numbers, dates, or date − ms
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while writing subtraction expressions.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $subtract: [ <a>, <b> ] } → a − b
NumbersNumeric difference
Two datesDifference in milliseconds
Date − numberNumber is milliseconds; date must be first
Days from msDivide by 86400000 with $divide
Sample check$subtract([10, 3]) → 7; total = (price + fee) − discount

Live Preview

Watch $subtract compute a − b for simple sale totals. Try price only, or price + fee minus discount.

Simulates $subtract (same idea as the mongosh examples below).

Result
a = 10
b = 5

$subtract → 5

{ total: 5 }

Worked Walkthrough — Sale Total

One sale has price 10, fee 2, and discount 5. Total is (price + fee) − discount.

Calculation
Document:
  { item: "abc", price: 10, fee: 2, discount: 5 }

subtotal = price + fee
         = 10 + 2
         = 12

total = subtotal − discount
      = 12 − 5
      = 7

$subtract([
  { $add: ["$price", "$fee"] },
  "$discount"
]) → 7

Check: 10 + 2 − 5 = 7 ✓

MongoDB Examples

We store one sale with price, fee, and discount. First we subtract the discount from price, then we nest $add for a full total. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine one sale for item abc with price 10, fee 2, and discount 5. We save it in a collection named sales.

mongosh
db.sales.insertOne({
  _id: 1,
  item: "abc",
  price: 10,
  fee: 2,
  discount: 5
});

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps one document in sales. Run find() to see it:

mongosh
db.sales.find()

Read that document like this:

Field in MongoDBValuePlain English
price10Item price before fees
fee2Extra charge to add
discount5Amount to subtract
Picture
price 10
+ fee   2
− disc  5
--------
total   7

How It Works

  1. Insert once. insertOne adds a single sales document.
  2. Numbers stay as written. Price, fee, and discount are plain numbers.
  3. find() shows the same shape. What you inserted is what you get back—ready for $subtract next.

Example 2 — Subtract Discount from Price

Goal: compute price − discount with a simple two-argument $subtract.

mongosh
db.sales.aggregate([
  {
    $addFields: {
      afterDiscount: {
        $subtract: ["$price", "$discount"]
      }
    }
  }
]);

How It Works

  1. Read the stored numbers. MongoDB already has price: 10 and discount: 5.
  2. Order matters. First argument is kept; second is removed → 10 − 5.
  3. Result is 5. Stored as afterDiscount.
  4. Keep all fields. $addFields does not delete price or discount.

Example 3 — Nested Total (Add then Subtract)

Same sale: add price and fee first, then subtract the discount to get the final total.

mongosh
db.sales.aggregate([
  {
    $addFields: {
      total: {
        $subtract: [
          { $add: ["$price", "$fee"] },
          "$discount"
        ]
      }
    }
  }
]);

How It Works

  1. Same stored document. Still using price 10, fee 2, discount 5.
  2. Add first. $add builds the subtotal 12.
  3. Subtract discount. $subtract([12, 5]) → 7.
  4. Easy check. 10 + 2 − 5 = 7.

Edge Cases & Pitfalls

Check these before using $subtract in production pipelines.

order

First minus second

$subtract([a, b]) is a − b, not b − a. Swap arguments and the sign flips.

null

Null operands become null

If either side is null or missing, the result is null. Use $ifNull when you want 0.

dates

Date − number needs date first

To subtract milliseconds from a date, put the date in argument 1. Two dates return milliseconds, not calendar days—use $dateDiff for day/month units.

arity

Exactly two arguments

Unlike $add, you cannot pass a long list. Nest expressions or subtract step by step.

Performance Notes

ApproachCostBest for
$subtract alonePer-document arithmeticSimple field differences
$add + $subtractStill O(docs)Totals with fees and discounts
Date − datePer-document ms differenceAge / duration in milliseconds

Arithmetic is cheap compared with large sorts or joins. Filter early with $match when only some documents need a computed total.

Key Takeaways

  • Role: first − second (numbers or dates).
  • Arity: exactly two arguments.
  • Totals: nest $add inside $subtract.
  • Dates: date − date → ms; date − ms → date.

One line: $subtract answers “what is the first value minus the second?”—for numbers, or for dates in milliseconds.

Frequently Asked Questions

$subtract returns the difference of two expressions: the first minus the second. For numbers, { $subtract: [ 10, 3 ] } returns 7. Use it inside aggregation expression stages such as $project and $addFields.
Use { $subtract: [ <expression1>, <expression2> ] }. The result is expression1 − expression2. Both can be field references, literals, or nested expressions.
Yes. Two dates → difference in milliseconds. A date minus a number (milliseconds) → a new date. To subtract a number from a date, the date must be the first argument.
$subtract takes exactly two operands (a − b). $add can sum multiple values. To subtract several numbers, nest $subtract or add negative values with $add.
If either operand is null or missing, $subtract returns null. Use $ifNull when missing values should be treated as zero.
Yes for numbers. Think of $subtract as MongoDB’s aggregation version of a - b—run it in the pipeline, not as a standalone find() filter.

Next: $switch

Branch on multiple conditions in an aggregation pipeline.

$switch tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

9 people found this page helpful