TExcelTAD
Home › MongoDB › Aggregation $group

Aggregation $group

$group collects documents that share a group key into one output document per key, and computes values for each group with accumulators.

js
{ $group: {
    _id: <group key expression>,      // required: what to group by
    <field>: { <accumulator>: <expression> },
    …
} }

Accumulators

Accumulator Computes
$sum sum of values ($sum: 1 counts documents)
$avg average
$min / $max smallest / largest value
$first / $last value from the first / last document of the group (sort before!)
$push array of all values
$addToSet array of distinct values
$count number of documents ({ $count: {} })
$top / $bottom / $topN the best document(s) by a sort order

Grouping by one field

Product statistics per category:

mongosh · try it yourself
print(db.products.aggregate([
  { $group: {
      _id: '$category',
      products: { $sum: 1 },
      avgPrice: { $avg: '$price' },
      cheapest: { $min: '$price' },
      units: { $sum: '$stock' }
  } },
  { $sort: { _id: 1 } }
]).toArray());
[
  {
    _id: 'coffee',
    products: 5,
    avgPrice: 22,
    cheapest: 18,
    units: 139
  },
  {
    _id: 'equipment',
    products: 6,
    avgPrice: 40.5,
    cheapest: 6,
    units: 154
  },
  { _id: 'merch', products: 1, avgPrice: 16, cheapest: 16, units: 25 },
  {
    _id: 'snacks',
    products: 4,
    avgPrice: 5.125,
    cheapest: 3.5,
    units: 165
  },
  {
    _id: 'tea',
    products: 4,
    avgPrice: 10.125,
    cheapest: 8,
    units: 128
  }
]

The whole collection as one group

Use _id: null to summarise every document together:

mongosh · try it yourself
print(db.orders.aggregate([
  { $match: { status: { $ne: 'cancelled' } } },
  { $group: {
      _id: null,
      orders: { $sum: 1 },
      revenue: { $sum: '$total' },
      averageOrder: { $avg: '$total' },
      biggest: { $max: '$total' }
  } },
  { $set: { averageOrder: { $round: ['$averageOrder', 2] } } }
]).toArray());
[
  {
    _id: null,
    orders: 18,
    revenue: 965.5,
    averageOrder: 53.64,
    biggest: 121
  }
]

The last stage rounds the average to cents; $set (an alias of $addFields) is covered in its own lesson.

Grouping by several fields

The group key can be a document. Here orders are counted per month and status. $month extracts the month number from a date:

mongosh · try it yourself
db.orders.aggregate([
  { $group: { _id: { month: { $month: '$date' }, status: '$status' }, n: { $sum: 1 } } },
  { $sort: { '_id.month': 1, '_id.status': 1 } }
]).forEach(g => print(g._id.month, g._id.status, g.n));
3 cancelled 1
3 delivered 7
4 delivered 2
4 shipped 3
5 cancelled 1
5 delivered 1
5 processing 3
6 processing 2

Collecting values: $push and $addToSet

mongosh · try it yourself
print(db.orders.aggregate([
  { $match: { status: 'delivered' } },
  { $group: { _id: '$customerId', orderIds: { $push: '$_id' } } },
  { $sort: { _id: 1 } }
]).toArray());

print(db.products.aggregate([
  { $unwind: '$tags' },
  { $group: { _id: '$category', tags: { $addToSet: '$tags' } } },
  { $match: { _id: 'tea' } },
  { $project: { tags: { $sortArray: { input: '$tags', sortBy: 1 } } } }
]).toArray());
[
  { _id: 1, orderIds: [ 1001, 1005 ] },
  { _id: 2, orderIds: [ 1003, 1011 ] },
  { _id: 3, orderIds: [ 1002, 1008 ] },
  { _id: 5, orderIds: [ 1004 ] },
  { _id: 6, orderIds: [ 1007 ] },
  { _id: 9, orderIds: [ 1009 ] },
  { _id: 10, orderIds: [ 1014 ] }
]
[
  {
    _id: 'tea',
    tags: [
      'bags',
      'black',
      'decaf',
      'green',
      'herbal',
      'loose-leaf',
      'spiced'
    ]
  }
]

$addToSet returns its values in no particular order, so the second pipeline sorts the array with $sortArray before printing.

The best document per group

To find, for each category, the highest-rated product, $top takes a sort order and an output expression:

mongosh · try it yourself
db.products.aggregate([
  { $group: {
      _id: '$category',
      best: { $top: { sortBy: { rating: -1, _id: 1 }, output: ['$name', '$rating'] } }
  } },
  { $sort: { _id: 1 } }
]).forEach(g => print(g._id.padEnd(10), g.best));
coffee     [ 'Ethiopia Yirgacheffe', 4.9 ]
equipment  [ 'Pour-Over Dripper', 4.8 ]
merch      [ 'Travel Mug', 4.3 ]
snacks     [ 'Dark Chocolate Bar', 4.8 ]
tea        [ 'Masala Chai', 4.6 ]

Note: The older way is to $sort first and use $first in the group. It still works, but $top/$topN say what you mean and don't depend on the incoming order.

Common mistakes

  • Forgetting the $ in field paths. { $sum: 'total' } sums the string "total" (giving 0); write '$total'.
  • Expecting the original fields after $group. Only _id and the accumulators survive. Collect what you need with $first, $push or $top.
  • Grouping on a field that some documents lack. They all fall into the group _id: null.

Test yourself

Which accumulator counts the documents in each group?

  1. { $count: '$_id' }
  2. { $sum: 1 }
  3. { $avg: 1 }
  4. { $push: 1 }

How do you compute a single grand total over all documents?

  1. _id: '$all'
  2. _id: null
  3. Omit _id
  4. _id: 1

{ $sum: 'price' } (no $) returns what?

  1. The sum of prices
  2. 0, because 'price' is a string literal, not a field path
  3. An error
  4. The number of documents