$reduce is a MongoDB aggregation expression that folds an array into one value. It walks each element, updates an accumulator, and returns the final result—like JavaScript’s Array.reduce().
Remember
$reduce = fold array → one value
{ $reduce: {
input: <array>,
initialValue: <start>,
in: <expression>
}
}
inside in:
$$value → accumulator (so far)
$$this → current element
empty array → initialValue
null input → null
Set input to the array field (for example "$scores").
Set initialValue (for a sum, start at 0).
In in, combine $$value and $$this (for example with $add).
Piece
Required?
Role
input
Yes
Array to walk
initialValue
Yes
Starting accumulator
in
Yes
How to update using $$value + $$this
Pseudocode
Pseudocode
arr = evaluate(input)
if arr is null or missing:
result = null
else:
acc = evaluate(initialValue)
for each element in arr:
$$this = element
$$value = acc
acc = evaluate(in)
result = acc
emit { ..., field: result }
Reference
Cheat Sheet
Keep these facts handy while folding arrays in pipelines.
Topic
Detail
Type
Aggregation expression (returns one value)
Syntax
{ $reduce: { input, initialValue, in } }
Variables
$$value · $$this
vs $map
One value vs new array
Empty array
Returns initialValue
Null input
Returns null
Sample sum
[10, 20, 30] → 60
Try it
Live Preview
Watch $reduce fold [10, 20, 30] into a sum, a max, or a joined string.
Simulates { $reduce: { input, initialValue, in } }.
We use one student with three scores. First insert the sample, then sum with $reduce, then join tags into one string. Run these in mongosh after inserting the sample data once.
Example 1 — Sample Data
Imagine student Asha with quiz scores 10, 20, 30 and tags math / quiz. We save the document in a collection named students.
$reduce visits every element once. That is fine for short arrays; avoid folding very large arrays on hot paths when a simpler operator will do.
Remember
Key Takeaways
Role: fold an array into one final value.
Parts:input + initialValue + in.
Vars:$$value (so far) · $$this (current).
Sample:[10, 20, 30] → total 60.
One line:$reduce answers “walk this array and keep updating one accumulator until one answer remains.”
Frequently Asked Questions
$reduce folds an array into a single value by walking each element and updating an accumulator. It is like JavaScript’s Array.reduce() inside an aggregation expression.
Use { $reduce: { input: <array>, initialValue: <expression>, in: <expression> } }. Inside in, $$value is the accumulator and $$this is the current element.
Use $$value for the running result and $$this for the current array item. Both need the double-dollar prefix.
$reduce returns initialValue. No elements run, so the accumulator never changes.
$map returns a new array with one result per element. $reduce returns one final value—sum, max, joined string, and so on.
If input is null or missing, $reduce returns null.