Pipelines With Several Stages

Most real questions need several stages. "Which three years got the most votes?" breaks into small steps, and each step is a stage:

db.movies.aggregate([
  { $group: { _id: "$year", votes: { $sum: "$votes" } } },
  { $sort: { votes: -1 } },
  { $limit: 3 }
])

Output:

[
  { _id: 2014, votes: 3600 },
  { _id: 2010, votes: 2400 },
  { _id: 2017, votes: 2200 }
]

$group adds up the votes for each year. $sort puts the years with the most votes first. $limit keeps the first three. $sort and $limit work like .sort() and .limit() on a find, but here they work on the group results.

Many pipelines follow this pattern: $match to filter, $group to combine, $sort to order, and $limit to keep the top results. You can add $project to tidy the output.

The order of stages matters. A $match before $group filters movies. A $match after $group filters the groups, for example years with more than 2000 votes.

To build a long pipeline, start with the first stage and run it. Look at the result, then add the next stage and run it again.

In the exercise, find the director whose movies got the most votes.