MongoDB $add Operator

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

What You’ll Learn

The $add operator adds numbers together in MongoDB aggregation pipelines. It is one of the most common arithmetic operators — perfect for calculating totals, combining field values, or adding milliseconds to dates.

01

Addition

Sum two or more values.

02

Array Syntax

Pass operands in an array.

03

Field Math

Add document fields together.

04

Date Math

Add milliseconds to dates.

05

Use Cases

Totals, tax, shipping.

06

Null Safety

Know how null inputs behave.

Definition and Usage

In MongoDB’s aggregation framework, the $add operator sums numeric expressions. For example, { $add: [ "$price", "$tax" ] } returns the combined total of two fields. You can also add a literal number to a field, or add multiple values in one expression.

💡
Beginner Tip

Unlike $abs or $acos, $add always takes an array of at least two expressions. Think of it as MongoDB’s pipeline version of the + operator.

📝 Syntax

The $add operator takes an array of two or more expressions:

mongosh
{ $add: [ <expression1>, <expression2>, ... ] }

Syntax Rules

  • $add — returns the sum of all expressions in the array.
  • Array required — always wrap operands in square brackets, even for two values.
  • Operands can be field paths ("$price"), literals (10), or nested expressions.
  • Use inside stages like $project, $addFields, or $set.
  • If any operand is null, the result is null.
  • When one operand is a Date and another is a number, the number is treated as milliseconds.

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (arithmetic)
Syntax{ $add: [ expr1, expr2, ... ] }
Minimum operands2 (array of at least two expressions)
Date supportYes — number operand = milliseconds
Common stages$project, $addFields, $set
Two fields
{
  $add: ["$a","$b"]
}

Sum of two fields

Field + literal
{
  $add: ["$qty", 1]
}

Add a constant

Three values
{
  $add: ["$a","$b","$c"]
}

Sum multiple fields

Null input
{
  $add: [null, 5]
}

Returns null

Examples Gallery

Walk through sample orders, add field values together, and compute totals in aggregation pipelines.

📚 Adding Field Values

Start with an orders collection and sum numeric fields using $project.

Sample Input Documents

Suppose you have an orders collection with price and tax fields:

mongosh
[
  { "_id": ObjectId("609c26812e9274a86871bc6a"), "price": 100, "tax": 18, "shipping": 5 },
  { "_id": ObjectId("609c26812e9274a86871bc6b"), "price": 250, "tax": 45, "shipping": 10 },
  { "_id": ObjectId("609c26812e9274a86871bc6c"), "price": 75,  "tax": 14, "shipping": 5 }
]

Example 1 — Basic $add with Two Fields

Add price and tax to get a subtotal:

mongosh
db.orders.aggregate([
  {
    $project: {
      price: 1,
      tax: 1,
      subtotal: { $add: [ "$price", "$tax" ] }
    }
  }
])

How It Works

  • Document 1: 100 + 18 = 118
  • Document 2: 250 + 45 = 295
  • Document 3: 75 + 14 = 89

📈 Practical Patterns

Sum multiple fields, compute order totals, and perform date arithmetic.

Example 2 — Add Three Fields for Order Total

Include shipping in the total by adding three fields at once:

mongosh
db.orders.aggregate([
  {
    $project: {
      price: 1,
      tax: 1,
      shipping: 1,
      orderTotal: {
        $add: [ "$price", "$tax", "$shipping" ]
      }
    }
  }
])

How It Works

$add accepts any number of operands in the array. MongoDB sums them left to right and returns the total.

Example 3 — Add a Literal Bonus Amount

Combine a field with a fixed literal value using $addFields:

mongosh
db.employees.aggregate([
  {
    $addFields: {
      bonusAmount: 5000,
      totalPay: { $add: [ "$salary", 5000 ] }
    }
  },
  {
    $project: {
      name: 1,
      salary: 1,
      bonusAmount: 1,
      totalPay: 1
    }
  }
])

How It Works

Literals and field references can be mixed freely inside the $add array. This is useful for flat fees, bonuses, or fixed surcharges.

Example 4 — Add Milliseconds to a Date

When one operand is a date, the number is treated as milliseconds. One day = 86,400,000 ms:

mongosh
db.shipments.aggregate([
  {
    $project: {
      orderDate: 1,
      deliveryDate: {
        $add: [ "$orderDate", 86400000 ]
      },
      deliveryAfter3Days: {
        $add: [ "$orderDate", 259200000 ]
      }
    }
  }
])

How It Works

$add on dates adds milliseconds. Multiply days by 86400000 (24 × 60 × 60 × 1000) to shift dates forward in pipelines.

🚀 Use Cases

  • Order totals — sum price, tax, shipping, and discount-adjusted amounts.
  • Financial reporting — combine revenue streams or add fees to base amounts.
  • Inventory counts — add stock from multiple warehouses into a total.
  • Date calculations — compute delivery dates, expiry dates, or deadlines in pipelines.

🧠 How $add Works

1

MongoDB evaluates each operand

The pipeline resolves every expression in the array — fields like "$price", literals, or nested operators.

Input
2

$add sums the values

For numbers, MongoDB adds them together. For dates, the numeric operand is treated as milliseconds.

Compute
3

The result is stored in the pipeline

The sum is written to the field you define in $project or $addFields.

Output
=

Computed total ready

Use the result for sorting, grouping, filtering, or displaying in reports.

Conclusion

The $add operator is one of the most frequently used tools in MongoDB aggregation pipelines. It lets you sum field values, add constants, combine multiple numbers, and perform basic date arithmetic — all without leaving the database.

For beginners, the key idea is simple: pass an array of expressions to { $add: [...] } inside a stage like $project, and MongoDB returns the sum.

💡 Best Practices

✅ Do

  • Always wrap operands in an array: { $add: [ a, b ] }
  • Use $ifNull to replace missing values before adding
  • Combine with $round for currency totals
  • Use $subtract for discounts before or after adding
  • Remember date operands use milliseconds

❌ Don’t

  • Forget the array syntax — { $add: "$a", "$b" } is invalid
  • Assume null fields become zero (they produce null)
  • Use $add as a query filter outside expressions
  • Mix incompatible types without checking your data
  • Confuse $add with the $sum accumulator in $group

Key Takeaways

Knowledge Unlocked

Five things to remember about $add

Use these points when writing your next aggregation pipeline.

5
Core concepts
📝 02

Array Syntax

{ $add: [a, b] }

Syntax
🛠 03

Multiple Operands

Add 3+ fields at once.

Flexibility
📅 04

Date Math

Number = milliseconds.

Dates
05

Null Aware

null in → null out.

Edge case

❓ Frequently Asked Questions

$add adds two or more numbers together in an aggregation pipeline. It can also add a number of milliseconds to a date field. Use it inside expression stages like $project and $addFields.
The syntax is { $add: [ <expression1>, <expression2>, ... ] }. You must pass an array with at least two expressions — field references, literals, or nested expressions.
Yes. $add accepts an array of two or more expressions and returns the sum of all of them.
Yes. When one operand is a date and another is a number, MongoDB treats the number as milliseconds and adds it to the date.
If any argument to $add is null, the result is null. Use $ifNull to provide a default before adding.

Continue the Operator Series

Move on to $allElementsTrue or review $subtract for the opposite operation.

Next: $allElementsTrue →

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