Skip to content

Aggregation Expressions

Arithmetic Expressions

$add, $subtract, $multiply, $divide and $mod inside $project and $group.

IntermediateAbout 5 minutes

An expression computes a value inside a stage. Operands are an array. Field paths start with $. You already used { $multiply: ["$price", "$stock"] } in $set. The rest of arithmetic is the same shape.

db.products.aggregate([
  { $match: { name: "Mechanical Keyboard" } },
  {
    $set: {
      inventoryValue: { $multiply: ["$price", "$stock"] },
      discounted: { $multiply: ["$price", 0.9] },
      remainder: { $mod: ["$price", 1000] }
    }
  }
])
Line math on a product, then a 10% cut
{ name: "Mechanical Keyboard", price: 4500, stock: 20, inventoryValue: 90000, discounted: 4050, remainder: 500 }
OperatorUse
$add / $subtractSums, diffs; $add also adds milliseconds to a date
$multiply / $divideScale and ratios
$modRemainder
$roundMoney: { $round: ["$price", 2] }
db.orders.aggregate([
  { $unwind: "$items" },
  {
    $group: {
      _id: "$items.name",
      revenue: { $sum: { $multiply: ["$items.quantity", "$items.unitPrice"] } }
    }
  }
])
Inside $group — sum of an expression, not a stored field

null in, null out — { $multiply: ["$price", "$missing"] } is null, not 0. $divide by 0 is null on current servers; still guard with $cond if zero stock is real data. $add with one date and numbers is date arithmetic — the dates lesson. Query $gt is not this: { price: { $gt: 100 } } filters. { $gt: ["$price", "$stock"] } is an expression, and in $match it needs $expr.

Interview question

How do aggregation arithmetic expressions differ from query operators?

Think about it first.