Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 70 ยท Aggregation pipeline

Grouping with $group

Summarize documents with the $group stage: choose an _id key, use $sum, $avg, $min, $max, $first, $push and $addToSet, count, and group by several fields.

Filtering and sorting still leave you with individual documents. Reports need summaries: total revenue per region, the number of orders per customer, the cheapest product in each category. In SQL that is GROUP BY with functions such as SUM; in the aggregation pipeline it is the $group stage (compare SQL GROUP BY if you know SQL).

$group takes the incoming documents, sorts them into buckets by a key you choose, and emits one document per bucket, with values computed from all documents that fell into it. It is the most important stage in the pipeline, so we will go through it step by step.

MongoDB cannot run on this site. The mongosh blocks are real commands shown read-only. The runnable examples use a stand-in pipeline engine written in plain JavaScript. The engine code sits at the top of each example; the pipeline you should read is at the bottom. It supports only the stages and operators used in this lesson.

The shape of $group

_id The key that defines the buckets.
Accumulators One computed field per bucket.
One output each One document per distinct key.
1 / 2

The shape of $group

The stage has one required field, _id, which says what to group by. Every other field is an accumulator: a name you pick, mapped to an operator that is applied to all documents of the bucket.

JavaScript
db.orders.aggregate([
  {
    $group: {
      _id: "$region",
      revenue: { $sum: { $multiply: ["$qty", "$price"] } },
      orders:  { $sum: 1 },
      biggest: { $max: "$qty" }
    }
  }
])

"$region" is a field path: the dollar sign means "the value of this field in the current document". The output has one document per distinct region, such as { _id: "north", revenue: 560, orders: 4, biggest: 6 }. Note that the grouping key lands in _id, whatever you call it in your head. You can rename it in a later $project stage.

The order of the output documents is not defined. A real server may return the groups in any order, and it can change between runs. Add a $sort stage after $group whenever order matters.

The accumulators

Accumulator Result for each bucket
$sum: expr Sum of the numeric values of expr. Non-numbers and missing values are ignored; $sum: 1 counts documents.
$avg: expr Average of the numeric values; null if there are none.
$min / $max: expr Smallest or largest value, ignoring null and missing values. Works on dates and strings too.
$first / $last: expr Value from the first or last document in the bucket. Only meaningful if you $sort before $group.
$push: expr Array of all values, duplicates included, in input order.
$addToSet: expr Array of the distinct values, in no guaranteed order.
$count: {} Number of documents in the bucket (MongoDB 5.0 and later); the same as $sum: 1.

Three practical points:

  • Counting is { $sum: 1 }: every document adds one.
  • $avg ignores non-numeric values, so a missing price does not count as zero; it is left out of both sum and count.
  • $push and $addToSet can grow large. A bucket's array must still fit in a 16 MB document (Documents, JSON and Field Types), so do not push millions of values.
JS Totals and averages per category

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Choosing the _id

The _id of $group can be any expression, and each distinct result becomes one bucket.

  • A field path: _id: "$region" groups by region.
  • null (or any constant): everything goes into one bucket, which gives grand totals such as total revenue or the average of the whole collection.
  • An expression: _id: { $year: "$createdAt" } groups by year. The date operators are covered in Expressions and Operators.
  • A document: _id: { region: "$region", category: "$category" } groups by a combination of fields, one bucket per distinct pair.

Documents that lack the grouping field are not skipped: they all fall into the bucket whose key is null. If that bucket is unwanted, filter earlier with $match: { region: { $exists: true } }.

Grouping by multiple fields

With a document as _id, the output _id is that document, so you read the parts as _id.region and _id.category. A common follow-up is a $project that flattens it:

JavaScript
db.orders.aggregate([
  { $group: { _id: { region: "$region", category: "$category" }, total: { $sum: "$amount" } } },
  { $project: { _id: 0, region: "$_id.region", category: "$_id.category", total: 1 } }
])

Counting distinct values

There is no $countDistinct accumulator. Instead group twice: first by the value you want to count, then group everything into one bucket and count the buckets.

JS Multi-field keys, $push, $addToSet and $first

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common patterns

Top N per group. Sort descending, then group and $push the values you need, then trim the array in a later stage (you will see $slice and array operators in Working with Arrays in Pipelines).

Group then filter. A $match after $group filters buckets, like SQL's HAVING. For example, "regions with more than 100 orders" is a $group with { $sum: 1 } followed by { $match: { orders: { $gt: 100 } } }. A $match before $group filters documents instead, like WHERE; it is almost always the better place for conditions on single documents.

Fewer fields in, faster group. $group needs only the fields it uses. A $project is not required (the server tracks which fields are used), but a $match in front is.

Memory. $group keeps its buckets in memory. A stage is limited to 100 MB of RAM by default; for huge cardinality you can pass allowDiskUse: true to aggregate, and recent server versions may spill to disk by default. See Aggregation Performance and Explain.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does { $group: { _id: null, n: { $sum: 1 } } } produce?

    A constant _id puts every document in one bucket, and $sum: 1 adds one per document, so you get a single count.
  2. 2. In which order does $group return its buckets?

    The output order of $group is undefined. Sort afterwards when order matters.
  3. 3. You want the first order date per customer. What must you do before $group?

    $first and $last depend on the order of the documents entering the stage, so sort first.
  4. 4. How do you group by the pair (region, category)?

    Using a document as _id creates one bucket per distinct combination of its values.
  5. 5. A price field is missing in one document. What does $avg: "$price" do with it?

    $avg considers only numeric values, so a missing price does not pull the average down.

Summary

  • $group buckets documents by _id and emits one document per bucket, with accumulators computed over each bucket.
  • Common accumulators are $sum (also $sum: 1 for counting), $avg, $min, $max, $first, $last, $push and $addToSet.
  • _id can be a field path, null for one grand-total bucket, an expression, or a document for multi-field keys.
  • Output order is undefined; add $sort, and sort before $group when you rely on $first or $last.
  • A $match before $group works like WHERE; after it, like HAVING.

Next, build computed values with Expressions and Operators.