What does the $group stage do?
The $group stage groups documents by one or several fields and lets you compute aggregates - sum, count, max, min, average, and so on. It's the analog of GROUP BY in SQL.
What happens inside
- documents get combined by a key (the field specified in
_id) - aggregate values are computed for each group (
$sum,$avg,$max,$min,$push, and others) - the result is a set of new documents, one per group
Example
js
{
$group: {
_id: "$status",
total: { $sum: 1 }
}
}Result: the count of documents in each status group.
The key point
In $group, the _id field is the grouping key. Everything that isn't _id has to be an aggregate operation.
Summary
$group is the stage that collects documents into groups and computes final values for each group, producing aggregated data.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.