$reduce
The $reduce operator applies an expression to each element in an array and accumulates the result.
📌 Syntax
{
"$reduce": {
"input": <arrayExpression>,
"initialValue": <expression>,
"in": <accumulatorExpression>
}
}
input: The array to iterateinitialValue: The starting value of the accumulatorin: Expression that updates the accumulator using$$valueand$$this
✅ Base Example – Sum Values
📥 Input Document
{ "nums": [1, 2, 3, 4] }
📌 Expression
{
"$reduce": {
"input": "$nums",
"initialValue": 0,
"in": { "$add": ["$$value", "$$this"] }
}
}
📤 Output
10
✅ Base Example – Concatenate Strings
📥 Input Document
{ "words": ["hello", "world"] }
📌 Expression
{
"$reduce": {
"input": "$words",
"initialValue": "",
"in": { "$concat": ["$$value", " ", "$$this"] }
}
}
📤 Output
" hello world"
🧱 Ecommerce Example – Total Price of All Items
📌 Pipeline
[
{
"$project": {
"total": {
"$reduce": {
"input": "$items",
"initialValue": 0,
"in": {
"$add": ["$$value", { "$multiply": ["$$this.price", "$$this.quantity"] }]
}
}
}
}
}
]
📥 Input Document
{
"items": [
{ "name": "Book", "price": 20, "quantity": 2 },
{ "name": "Bag", "price": 50, "quantity": 1 }
]
}
📤 Output
{ "total": 90 }
🔧 Common Use Cases
- Compute totals or nested accumulations
- String aggregation
- Custom transformations
🔗 Related Operators
$map,$filter,$concat,$sum,$avg
🧠Notes
$$valuerefers to the accumulator$$thisrefers to the current array element