Learn › Aggregation
Grouping and accumulators
$group, $sum, $avg, $min, $max, $first — turning many documents into few.
By the end: Aggregate a collection down to one row per key.
Lessons
- $group: the heart of aggregation
MongoDB $group explained: _id is the grouping key, everything else is an accumulator. The stage most people stall on.
- Counting and summing
Count documents and sum fields per group in MongoDB with $group and $sum, including the $sum: 1 counting idiom.
- The accumulator operators
The MongoDB $group accumulators: $sum, $avg, $min, $max, $count, $push, $addToSet, $first and $last.
- $push vs $addToSet inside $group
MongoDB $push vs $addToSet inside $group: collect every value, or collect the distinct ones. Pair $addToSet with $size to count them.
- Grouping by more than one field
Group by more than one field in MongoDB by making $group _id an object, and how that changes the shape of your results.
- $first and $last
MongoDB $first and $last pick a value from each group, and both depend entirely on the $sort you ran beforehand.