$group: Combining Documents

$group puts documents into groups and makes one result document for each group:

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

Output:

[
  { _id: 2010, films: 1 },
  { _id: 2014, films: 2 },
  { _id: 2016, films: 1 },
  { _id: 2017, films: 2 },
  { _id: 2018, films: 1 },
  { _id: 2019, films: 1 }
]

Read the $group stage one part at a time:

  • _id: "$year" says what to group by. Movies with the same year go into the same group, and the year becomes the _id of the result.
  • films: { $sum: 1 } creates a field called films. For each movie in the group it adds 1, so it counts the movies.

$sum is an accumulator. An accumulator collects one value from all the documents in a group. Here are the common ones:

AccumulatorGives you
$sum: 1the number of documents
$sum: "$votes"the total of a field
$avgthe average of a field
$min, $maxthe smallest or largest value
$pushan array of all the values

A group can have several accumulators:

db.movies.aggregate([
  { $match: { director: "Bong Joon-ho" } },
  { $group: {
    _id: "$director",
    avgRating: { $avg: "$rating" },
    best: { $max: "$rating" }
  } }
])

Output:

[ { _id: 'Bong Joon-ho', avgRating: 8.15, best: 8.5 } ]

MongoDB does not promise the order of $group results. That is why the first example has a $sort stage after $group. The second example has only one group, so order does not matter there.

In the exercise, count the movies of each director.