The $group stage helps you collect and combine data by categories, like counting or summing values for each group.
$group stage for aggregation in MongoDB
Introduction
Syntax
MongoDB
db.collection.aggregate([
{
$group: {
_id: <expression>,
<field1>: { <accumulator1> : <expression1> },
<field2>: { <accumulator2> : <expression2> },
...
}
}
])The _id field defines the group key (what you group by).
Accumulator operators like $sum, $avg, $max, and $min calculate values for each group.
Examples
customerId and summing 1 for each order.MongoDB
db.orders.aggregate([
{ $group: { _id: "$customerId", totalOrders: { $sum: 1 } } }
])MongoDB
db.sales.aggregate([
{ $group: { _id: "$product", totalSales: { $sum: "$amount" } } }
])MongoDB
db.movies.aggregate([
{ $group: { _id: "$genre", avgRating: { $avg: "$rating" } } }
])Sample Program
This query groups orders by customerId and counts how many orders each customer made.
MongoDB
db.orders.aggregate([
{ $group: { _id: "$customerId", totalOrders: { $sum: 1 } } }
])Important Notes
The _id field cannot be omitted; it defines how documents are grouped.
You can group by multiple fields by using an object in _id, like { customerId: "$customerId", status: "$status" }.
Summary
$group collects documents into groups based on a key.
Use accumulator operators to calculate sums, counts, averages, and more.
The _id field defines the grouping key and is required.
Practice
1. What is the main purpose of the
$group stage in a MongoDB aggregation pipeline?easy
Solution
Step 1: Understand the role of
The$group$groupstage collects documents into groups based on a key defined in the_idfield.Step 2: Identify what
It allows performing calculations like sum, count, or average on each group.$groupdoes with groupsFinal Answer:
To group documents by a specified key and perform calculations on each group -> Option DQuick Check:
$groupgroups and calculates [OK]
Hint: Remember:
$group always groups and aggregates [OK]Common Mistakes:
- Confusing
$groupwith$matchfor filtering - Thinking
$groupsorts documents - Assuming
$groupprojects fields without grouping
2. Which of the following is the correct syntax to group documents by the field
category and count the number of documents in each group?easy
Solution
Step 1: Identify the grouping key field
The grouping key must be assigned to_id, so_id: "$category"is correct.Step 2: Use the correct accumulator for counting
Counting documents uses$sum: 1to add 1 for each document in the group.Final Answer:
{ $group: { _id: "$category", count: { $sum: 1 } } } -> Option BQuick Check:
Group key in_idand count with$sum: 1[OK]
Hint: Always use
_id for group key and $sum: 1 to count [OK]Common Mistakes:
- Using field name instead of
_idfor grouping key - Using
$countinstead of$sumfor counting - Using
$addwhich is not an accumulator
3. Given the collection documents:
What will be the output of this aggregation?
{ "category": "A", "value": 10 }{ "category": "B", "value": 20 }{ "category": "A", "value": 15 }What will be the output of this aggregation?
[{ $group: { _id: "$category", total: { $sum: "$value" } } }]medium
Solution
Step 1: Group documents by
Documents with category "A" are grouped together, and category "B" separately.categoryStep 2: Sum the
For category "A": 10 + 15 = 25; for category "B": 20.valuefields in each groupFinal Answer:
[{ "_id": "A", "total": 25 }, { "_id": "B", "total": 20 }] -> Option AQuick Check:
Sum values per category = correct totals [OK]
Hint: Sum values grouped by
_id key field [OK]Common Mistakes:
- Expecting separate documents without grouping
- Summing incorrectly or ignoring grouping
- Using
_id: nullwhich groups all documents together
4. Identify the error in this aggregation pipeline stage:
{ $group: { category: "$category", total: { $sum: "$amount" } } }medium
Solution
Step 1: Check for required
The_idfield in$group_idfield is mandatory to specify the grouping key.Step 2: Verify other syntax elements
The$sumoperator and field references are correct; only_idis missing.Final Answer:
Missing_idfield for grouping key -> Option CQuick Check:
_idis required in$group[OK]
Hint: Always include
_id in $group stage [OK]Common Mistakes:
- Omitting the
_idfield - Confusing field names with grouping key
- Thinking
$sumneeds special syntax
5. You have a collection of sales documents with fields
store, item, and quantity. You want to find the total quantity sold per store, but only for stores where the total quantity exceeds 100. Which aggregation pipeline correctly achieves this?hard
Solution
Step 1: Group by
Thestoreand sumquantity$groupstage groups documents bystoreand calculates total quantity sold per store.Step 2: Filter groups where total quantity > 100
The$matchstage after grouping filters groups withtotalQuantitygreater than 100.Final Answer:
[{ $group: { _id: "$store", totalQuantity: { $sum: "$quantity" } } }, { $match: { totalQuantity: { $gt: 100 } } }] -> Option AQuick Check:
Group then filter by aggregated field [OK]
Hint: Filter after grouping using
$match on aggregated fields [OK]Common Mistakes:
- Filtering before grouping which filters documents, not groups
- Filtering on
_idinstead of aggregated field - Using
$sortinstead of filtering
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
