$group
$group collects documents into groups by a key and computes totals, averages and more for each group.
In this page:
Syntax
{ $group: {
_id: "$field",
total: { $sum: "$amount" },
average: { $avg: "$amount" }
} }
$group
The _id field of the $group stage defines the grouping key, and other fields hold accumulators such as $sum, $avg, $min, $max, $push and $addToSet.
Use _id: null to aggregate everything into one result. Group output order is not guaranteed, so add $sort.
Note:
$group output is unordered; follow it with $sort.
Example: $group
test> db.sales.insertMany([
... { _id: 1, item: "pen", qty: 5 }, { _id: 2, item: "book", qty: 1 },
... { _id: 3, item: "pen", qty: 10 }, { _id: 4, item: "book", qty: 3 }, { _id: 5, item: "lamp", qty: 2 }
... ])
{
acknowledged: true,
insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }
}
test> db.sales.aggregate([{ $group: { _id: "$item", totalQty: { $sum: "$qty" }, orders: { $sum: 1 } } }, { $sort: { _id: 1 } }])
[
{ _id: 'book', totalQty: 4, orders: 2 },
{ _id: 'lamp', totalQty: 2, orders: 1 },
{ _id: 'pen', totalQty: 15, orders: 2 }
]
test> db.sales.aggregate([{ $group: { _id: null, avgQty: { $avg: "$qty" }, maxQty: { $max: "$qty" } } }])
[ { _id: null, avgQty: 4.2, maxQty: 10 } ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Forgetting the _id key
- Expecting sorted output
- Using $sum: 1 versus $sum: "$field" incorrectly
Chapter Summary
- _id is the group key
- Accumulators: $sum $avg $min $max $push
- _id null groups everything
- Output is unordered
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: