How to Use $reduce in Aggregation in MongoDB
In MongoDB aggregation,
$reduce is used to iterate over an array and combine its elements into a single value by applying an expression. It requires input (the array), initialValue (starting value), and in (expression using $$value and $$this) to define how to accumulate results.Syntax
The $reduce operator has three main parts:
- input: The array to process.
- initialValue: The starting value for accumulation.
- in: An expression that defines how to combine the current accumulated value (
$$value) with the current array element ($$this).
json
{
$reduce: {
input: <array>,
initialValue: <any>,
in: <expression>
}
}Example
This example sums all numbers in an array field called values for each document.
mongodb
db.collection.aggregate([
{
$project: {
total: {
$reduce: {
input: "$values",
initialValue: 0,
in: { $add: ["$$value", "$$this"] }
}
}
}
}
])Output
[
{ "_id": 1, "total": 15 },
{ "_id": 2, "total": 10 }
]
Common Pitfalls
Common mistakes when using $reduce include:
- Not using
$$valueand$$thiscorrectly inside theinexpression. - Setting
initialValueto a wrong type that does not match the expected result. - Using
$reduceon a field that is not an array, which causes errors.
Always ensure the input is an array and the in expression properly combines $$value and $$this.
json
/* Wrong usage: missing $$value */ { $reduce: { input: "$values", initialValue: 0, in: { $add: ["$$this"] } // Error: missing $$value } } /* Correct usage: include $$value */ { $reduce: { input: "$values", initialValue: 0, in: { $add: ["$$value", "$$this"] } } }
Quick Reference
| Part | Description |
|---|---|
| input | The array to iterate over |
| initialValue | Starting value for accumulation |
| in | Expression combining $$value (accumulated) and $$this (current element) |
Key Takeaways
Use $reduce to combine array elements into a single value in aggregation.
Always provide input array, initialValue, and an in expression using $$value and $$this.
Ensure the input is an array to avoid errors.
The in expression defines how to accumulate results step-by-step.
Common errors come from missing $$value or wrong initialValue types.