Aggregation: Documents Through a Pipeline

find answers "which documents match?". Some questions need documents to be combined, like "how many movies does each director have?". For these, MongoDB has the aggregation pipeline. A pipeline is an array of stages. The documents go through the stages in order. Each stage changes them and passes the result to the next stage.

The simplest pipeline has one stage, $match. It filters documents in the same way as a find filter:

db.movies.aggregate([
  { $match: { director: "Bong Joon-ho" } }
])

Output:

[
  {
    _id: 3,
    title: 'Parasite',
    director: 'Bong Joon-ho',
    year: 2019,
    rating: 8.5,
    votes: 1800,
    genres: [ 'thriller', 'drama' ]
  },
  {
    _id: 6,
    title: 'Okja',
    director: 'Bong Joon-ho',
    year: 2017,
    rating: 7.8,
    votes: 900,
    genres: [ 'drama' ]
  }
]

This is the same result that find would give. The difference is that more stages can follow. Here, the documents from $match go into a $project stage, which works like a projection:

db.movies.aggregate([
  { $match: { rating: { $gte: 8.5 } } },
  { $project: { _id: 0, title: 1, rating: 1 } }
])

Output:

[
  { title: 'Inception', rating: 8.8 },
  { title: 'Interstellar', rating: 8.7 },
  { title: 'Parasite', rating: 8.5 },
  { title: 'Whiplash', rating: 8.5 }
]

Four movies passed the $match stage. Then $project kept two fields of each one. This is the main idea of aggregation: documents flow through the stages, from top to bottom. The rest of this section adds new kinds of stages.

When you can, put $match first. Then the later stages have fewer documents to work on.

In the exercise, write a pipeline with one $match stage.