$reduce (Reduce Array to Single Value)
Last updated: 2026-10-09
$reduce (Reduce Array to Single Value)
$reduce folds an array into a single value, the aggregation equivalent of functional reduce/fold. It takes an initialValue and an in expression where $$value is the accumulator and $$this is the current element. Typical uses: summing an array of numbers, joining strings, or counting elements that satisfy a condition. An empty array returns initialValue directly. $reduce is more general than $sum or $concat and can express arbitrary accumulation logic.
| Category | Array |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $reduce: { input: <array>, initialValue: <initialValue>, in: <reducer> } }
⚙️ Parameters
| input | The array to reduce. |
|---|---|
| initialValue | The starting value of the accumulator. |
| in | The reducer expression; $$value is the accumulator, $$this the current element. |
Returns:A single reduced value; empty array returns initialValue; null input yields null
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $reduce: sum the array
db.stats.aggregate([
{ $project: {
total: { $reduce: { input: '$scores', initialValue: 0, in: { $add: ['$$value', '$$this'] } } }
} }
])
Output:
{ '_id': 1, 'total': 285 }
📌 Notes
- Inside in, $$value is the accumulator and $$this is the current element; both are built-in
- An empty array returns initialValue without error
- The type of initialValue drives the result type: 0 yields numbers, '' yields strings
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QCan $reduce sum an array?
AYes — initialValue 0 with { $add: ['$$value', '$$this'] }; for plain numbers $sum works too.
QWhat happens with an empty array?
AIt returns initialValue directly, without error.
QWhat are $$value and $$this?
A$$value is the running result and $$this the current element; both exist only inside $reduce's in.