Lesson 18 +10 XP

$group and $count

$group and $count

$group groups documents by a key, and $count counts documents passing through the pipeline.

$group - group by a field

// One document per distinct property type
db.listingsAndReviews.aggregate([
  { $group: { _id: "$property_type" } }
])

The _id here is the grouping key - NOT the document's own _id ObjectId. Without any accumulators, $group behaves like SELECT DISTINCT.

Adding accumulators

Accumulators compute values within each group:

db.posts.aggregate([
  { $group: { _id: "$category", totalLikes: { $sum: "$likes" } } }
])

Common accumulators:

AccumulatorWhat it computes
$sumTotal of a field
$avgAverage of a field
$pushBuilds an array of values

$count - count the documents

$count takes a string that becomes the output field name, and returns a single document:

db.restaurants.aggregate([
  { $match: { cuisine: "Chinese" } },
  { $count: "totalChinese" }
])
// -> { "totalChinese": 445 }

$count collapses the whole pipeline into one document, so it should be near the end.

TL;DR

  • $group groups by a key (_id) with optional accumulators.
  • $sum, $avg, $push compute values within groups.
  • $count outputs a single document with the count.