querydrill

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

6
  1. $group: the heart of aggregation

    MongoDB $group explained: _id is the grouping key, everything else is an accumulator. The stage most people stall on.

  2. Counting and summing

    Count documents and sum fields per group in MongoDB with $group and $sum, including the $sum: 1 counting idiom.

  3. The accumulator operators

    The MongoDB $group accumulators: $sum, $avg, $min, $max, $count, $push, $addToSet, $first and $last.

  4. $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.

  5. 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.

  6. $first and $last

    MongoDB $first and $last pick a value from each group, and both depend entirely on the $sort you ran beforehand.

Drills

1 easy · 2 medium · 1 hard
Start reading →Skip to the drills