MongoDB $multiply Operator

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

What Is $multiply?

$multiply is a MongoDB aggregation expression that multiplies two or more numbers and returns the product. Classic use: price × quantity for a line total.

Remember
$multiply = * for aggregation

{ $multiply: [ <a>, <b>, ... ] }

$multiply([10, 2]) → 20
$multiply([5, 10]) → 50
$multiply([2, 3, 4]) → 24

null / missing arg → null
needs 2+ numbers in the array
UsePrefer
Product of numbers$multiply
Sum of numbers$add
Quotient$divide

How to Use $multiply in MongoDB

Pass an array of numeric expressions—fields, literals, or nested math.

  1. Choose an expression stage ($addFields or $project).
  2. List at least two numbers in { $multiply: [ ... ] }.
  3. Use field paths like "$price" and "$quantity" for line totals.
  4. Add more factors when needed (tax rate, discount factor, dimensions).
PieceRequired?Role
$multiplyYesComputes the product
Array of 2+ expressionsYesNumbers to multiply
Nested mathNoBuild factors before multiplying

Pseudocode

Pseudocode
for each document:
    values = evaluate each expression in the array
    if any value is null or missing:
        result = null
    else:
        result = 1
        for each n in values:
            result = result * n
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while writing products.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $multiply: [ <a>, <b>, ... ] }
ArityTwo or more arguments
Line total$multiply: ["$price", "$quantity"]
NullAny null/missing arg → null
Tip (6.1+)Put constants first, field refs last
Sample10 × 2 = 20, 5 × 10 = 50

Live Preview

Watch $multiply compute a product. Pick a pair (or trio), then run.

Simulates { $multiply: [ ... ] } (same idea as the mongosh examples below).

Result
$multiply([10, 2])
10 × 2 = 20

{ total: 20 }

Worked Walkthrough — Line Total

An item costs 10 and the customer buys 2. The line total is price × quantity.

Calculation
Document:
  { item: "abc", price: 10, quantity: 2 }

total = price × quantity
      = 10 × 2
      = 20

$multiply(["$price", "$quantity"]) → 20

Check: two units at $10 each = $20 ✓

MongoDB Examples

We use a small sales collection. First we compute line totals, then multiply three factors. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine three sales lines. Each has a price and a quantity. We save them in a collection named sales.

mongosh
db.sales.insertMany([
  { _id: 1, item: "abc", price: 10, quantity: 2, date: ISODate("2014-03-01T08:00:00Z") },
  { _id: 2, item: "jkl", price: 20, quantity: 1, date: ISODate("2014-03-01T09:00:00Z") },
  { _id: 3, item: "xyz", price: 5, quantity: 10, date: ISODate("2014-03-15T09:00:00Z") }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps three documents in sales. Run find() to see them:

mongosh
db.sales.find()

Read one document like this:

Field in MongoDBValue (doc 1)Plain English
item"abc"Product code
price10Unit price
quantity2Units sold

How It Works

  1. Insert once. insertMany adds three sale documents to sales.
  2. Two numbers per line. price and quantity are ready for $multiply.
  3. find() shows the same shape. What you inserted is what you get back.

Example 2 — Price × Quantity

Goal: compute each line’s total with $multiply.

mongosh
db.sales.aggregate([
  {
    $project: {
      item: 1,
      date: 1,
      total: { $multiply: ["$price", "$quantity"] }
    }
  }
]);

How It Works

  1. Read two fields. For doc 1: price: 10, quantity: 2.
  2. Multiply. $multiply: ["$price", "$quantity"] → 20.
  3. Repeat per document. Doc 2 → 20; doc 3 → 5 × 10 = 50.
  4. $project keeps listed fields (plus _id) and adds total.

Example 3 — Three Factors

Same sales, but apply a fixed tax factor of 1.1 (10% tax) on top of price × quantity.

mongosh
db.sales.aggregate([
  {
    $addFields: {
      withTax: {
        $multiply: ["$price", "$quantity", 1.1]
      }
    }
  }
]);

How It Works

  1. Three inputs. $multiply accepts more than two values in one array.
  2. Order of factors. 10 × 2 × 1.1 = 22 for the first sale.
  3. Literal constant. 1.1 is a number literal, not a field path.
  4. $addFields keeps originals. price and quantity stay; withTax is added.

Edge Cases & Pitfalls

Check these before using $multiply in production pipelines.

null

Any null makes the product null

Missing price or quantity yields null. Use $ifNull when zero (or another default) is safer.

count

Need at least two arguments

Pass an array with two or more expressions. A single value is not a valid $multiply call.

type

Operands must be numbers

Strings or other non-numeric types cause errors. Convert with $toDouble / $toDecimal when data is messy.

money

Prefer decimal for money

For currency, Decimal128 avoids float surprises. Mixing types promotes to the wider numeric type.

Performance Notes

ApproachCostBest for
$multiply alonePer-document mathLine totals / scaling
Many factorsStill O(docs)Tax, volume, compound rates
Constants first (6.1+)Small optimizer winLiterals + field refs together

Multiplication is cheap compared with large sorts or joins. Filter early with $match when only some documents need a product. From MongoDB 6.1, putting constants before field references can help the optimizer.

Key Takeaways

  • Role: multiply numbers → product.
  • Pattern: price × quantity for line totals.
  • Arity: two or more arguments in one array.
  • Null: any null/missing factor → null.

One line: $multiply answers “what is the product of these numbers?”—in aggregation, like *.

Frequently Asked Questions

$multiply multiplies two or more numbers and returns the product. Use it inside aggregation expression stages such as $project and $addFields—for example price × quantity for a line total.
The syntax is { $multiply: [ <expression1>, <expression2>, ... ] }. Pass an array of two or more numeric expressions: fields, literals, or nested math.
Yes. It multiplies every value in the array. Example: { $multiply: [ "$length", "$width", "$height" ] } computes volume.
If any argument is null or missing, $multiply returns null. Use $ifNull to supply a default before multiplying when fields may be absent.
$multiply returns a product. $add returns a sum. Both take an array of expressions in aggregation stages.
Yes for the math. Think of $multiply as MongoDB’s aggregation version of the * operator—run it in the pipeline, not as a standalone find() filter.

Next: $ne

Test whether two values are not equal in queries and aggregation.

$ne tutorial →

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