liveBook · Manning

$group

As explained in MongoDB 8.0 in Action, Third Edition

$group is a MongoDB aggregation pipeline stage that groups documents by an expression and computes aggregate results for each group.

$group is an aggregation pipeline stage that groups documents by an expression and computes aggregate values for each group. It emits one result document per distinct group, with the grouping expression stored in _id. section 6.1.1 section 6.1.2

Build a useful grouping pipeline by combining $group with surrounding stages:

  • Place $match before $group to reduce the documents that require aggregation. section 6.1.1 section 6.1.2
  • Set _id to the grouping expression, such as "$src_airport", and use accumulators such as $sum, $avg, $min, or $max. section 6.1.1 section 6.6
  • Follow the grouped results with stages such as $sort or $limit to order or restrict the returned groups. section 6.1.1

Count routes by source airport

A pipeline can filter routes for airplane type CR2, group them by source airport, count each group with { $sum: 1 }, sort by totalRoutes descending, and return the five busiest airports. The grouped output contains fields such as { _id: "DME", totalRoutes: 19 }. section 6.1.1

Listing 6.1 Executing an aggregation pipeline
db.routes.aggregate([
  {
    $match: { airplane: "CR2" } // Filter documents where the
➥airplane is "CR2"
  },
  {
    $group: {
      _id: "$src_airport",       // Group by source airport
      totalRoutes: { $sum: 1 }   // Count the number of routes
➥from each source
    }
  },
  {
    $sort: { totalRoutes: -1 }   // Sort the results by the
➥number of routes in descending order
  },
  {
    $limit: 5                    // Limit the number of displayed
➥documents to 5
  }
])


[
  { _id: 'DME', totalRoutes: 19 },
  { _id: 'SVX', totalRoutes: 17 },
  { _id: 'OVB', totalRoutes: 12 },
  { _id: 'LED', totalRoutes: 11 },
  { _id: 'OMS', totalRoutes: 8 }
]

Inspect the complete executable pipeline and its representative grouped output. section 6.1.1

let g = {
   $group: {
      _id: "$group_id",
      max_temp: {
         $avg: "$obs.temp"
      },
      avg_watts: {
         $avg: "$obs.watts"
      },
      median_watts: {
         $min: "$obs.watts"
      },
      max_watts: {
         $max: "$obs.watts"
      },
      min_watts: {
         $min: "$obs.watts"
      }
   }
}

Compare ordinary aggregation with streaming grouping, where grouped values are calculated inside a bounded tumbling window. section 15.6.6

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Demonstrates syntax, accumulators, pipeline placement, sorting, limiting, and window-bounded streaming, without detailing aggregation internals.
Examples
Uses route counts by source airport and solar-device temperature and wattage statistics within ten-second windows.
What it assumes
Assumes familiarity with MongoDB documents and pipeline syntax while demonstrating the grouping pattern from executable examples.
What you can do after
Apply it via MongoDB aggregation pipelines or Atlas Stream Processing to produce grouped analytical results.
How it connects
Connects $group with aggregation pipelines, $match, $sum, $sort, $limit, accumulators, tumbling windows, and $merge.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.