Aggregation Expressions
Arithmetic Expressions
$add, $subtract, $multiply, $divide and $mod inside $project and $group.
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] }
}
}
]){ name: "Mechanical Keyboard", price: 4500, stock: 20, inventoryValue: 90000, discounted: 4050, remainder: 500 }| Operator | Use |
|---|---|
| $add / $subtract | Sums, diffs; $add also adds milliseconds to a date |
| $multiply / $divide | Scale and ratios |
| $mod | Remainder |
| $round | Money: { $round: ["$price", 2] } |
db.orders.aggregate([
{ $unwind: "$items" },
{
$group: {
_id: "$items.name",
revenue: { $sum: { $multiply: ["$items.quantity", "$items.unitPrice"] } }
}
}
])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?
Query operators sit in a filter and compare a field to a value: { price: { $gt: 100 } }. Expressions compute a new value and take an array of operands: { $multiply: ["$price", "$stock"] }. The same names ($gt, $eq) exist in both; in $match you wrap field-vs-field comparisons in $expr.