$group: Aggregating and Computing Totals
Learners will group documents by a key and compute sums, averages, counts, and other accumulators with $group.
What Does $group Do?
The $group stage collapses multiple input documents into fewer output documents based on a grouping key. Documents that share the same key value are merged into a single output document, and accumulator operators compute aggregate values for each group. Think of it as MongoDB's equivalent of SQL's GROUP BY clause combined with aggregate functions like SUM and COUNT.
// Count orders per user
db.orders.aggregate([
{ $group: {
_id: '$userId', // group by userId
orderCount: { $sum: 1 } // count each document as 1
}}
]);
// Output: one doc per unique userId with their order countThe _id Field in $group
Every $group stage requires an _id field that defines the grouping key. The _id can be a field reference ('$field'), a computed expression, an object with multiple fields (for compound grouping), or null (to aggregate the entire collection into one document). The _id value in the output is the group key.
// Group by single field
{ $group: { _id: '$status' } }
// Group by multiple fields (compound key)
{ $group: { _id: { year: { $year: '$createdAt' }, status: '$status' } } }
// Group all documents into one (grand total)
{ $group: { _id: null, grandTotal: { $sum: '$amount' } } }
// Group by computed expression
{ $group: { _id: { $toLower: '$category' } } }All lessons in this course
- Pipeline Concepts: Stages, Operators, and Expressions
- $match and $project: Filter and Reshape
- $group: Aggregating and Computing Totals
- $sort, $limit, and $skip in the Pipeline