Loading lessons...
$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:
| Accumulator | What it computes |
|---|---|
| $sum | Total of a field |
| $avg | Average of a field |
| $push | Builds 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
$groupgroups by a key (_id) with optional accumulators.$sum,$avg,$pushcompute values within groups.$countoutputs a single document with the count.