liveBook · Manning

Aggregation pipeline

As explained in MongoDB 8.0 in Action, Third Edition

An aggregation pipeline processes documents through an ordered sequence of stages that filter, transform, combine, or summarize data.

An aggregation pipeline processes MongoDB documents through an ordered sequence of stages. Each stage receives the previous stage’s output and filters, reshapes, joins, or summarizes it. Use a pipeline when a simple query cannot produce the analysis or report you need. Breaking a complex transformation into stages also makes it easier to understand and debug. section 6.0 section 6.1

Build and run a collection pipeline with `db.collection.aggregate([ ... ])`. Common stages have distinct jobs:

  • `$match` selects documents; placing it early reduces work for later stages. section 6.1.2
  • `$group` combines documents by a key and can calculate sums or averages. `$set` and `$unset` change fields; reserve `$project` for a substantially different document shape. section 6.1.2 section 6.6
  • `$sort` orders results and `$limit` restricts how many proceed. Index fields used for sorting where appropriate; limiting results can reduce processing and memory use. section 6.1.2
  • `$unwind` produces a document for each array element, while `$lookup` joins related documents from another collection. section 6.1.2 section 6.6

Find the busiest source airports for one airplane type

Run `db.routes.aggregate([...])` with four stages: `$match` routes whose airplane is `CR2`; `$group` by source airport and count routes with `$sum: 1`; `$sort` the counts descending; then `$limit` the output to five airports. The resulting documents contain an airport identifier and its route count. 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 }
]

The complete routes command shows the stage order, field references, accumulator, and returned documents. section 6.1.1

An ordinary pipeline leaves collection documents unchanged. `$merge` and `$out` are exceptions that can write results to a collection. Check for a write stage before running a pipeline intended only for inspection. section 6.1.1

The same stage-based approach extends to Atlas Stream Processing, but a stream processor runs continuously: it starts with `$source`, processes incoming documents, and sends results to a destination. Operations over sets of streaming documents, including `$group`, require a time window rather than an unbounded stream. Some familiar stages therefore have different placement rules in streaming pipelines. section 15.3 section 15.5 section 15.5.3

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Works through an executable four-stage pipeline and gives stage-selection and performance guidance.
Examples
Counts routes by source airport through filtering, grouping, sorting, and limiting; also uses `$merge` to restore archived data.
What it assumes
Assumes familiarity with MongoDB collections and documents while defining the stages used in the worked pipeline.
What you can do after
Build it from scratch with `db.collection.aggregate()`, selecting and ordering stages for a reporting task.
How it connects
Connects aggregation to the MongoDB Query API, accumulators, collection joins, indexes, and Atlas Stream Processing.

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.