$group stage for aggregation in MongoDB - Time & Space Complexity
When using the $group stage in MongoDB aggregation, we want to know how the time to run the operation changes as the data grows.
We ask: How does grouping many documents affect the work MongoDB does?
Analyze the time complexity of the following code snippet.
db.orders.aggregate([
{ $group: {
_id: "$customerId",
totalAmount: { $sum: "$amount" }
}
}
])
This groups orders by customer ID and sums the amount spent by each customer.
Look for repeated work inside the aggregation.
- Primary operation: Scanning each document once to assign it to a group.
- How many times: Once per document in the collection.
As the number of documents grows, the work grows roughly the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 document checks and group assignments |
| 100 | About 100 document checks and group assignments |
| 1000 | About 1000 document checks and group assignments |
Pattern observation: The work grows linearly with the number of documents.
Time Complexity: O(n)
This means the time to group grows directly with the number of documents processed.
[X] Wrong: "Grouping always takes the same time no matter how many documents there are."
[OK] Correct: Grouping must look at each document to decide its group, so more documents mean more work.
Understanding how grouping scales helps you explain performance in real projects and shows you can think about data size effects clearly.
"What if we added a $match stage before $group to filter documents? How would that affect the time complexity?"
Practice
$group stage in a MongoDB aggregation pipeline?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]
$group always groups and aggregates [OK]- Confusing
$groupwith$matchfor filtering - Thinking
$groupsorts documents - Assuming
$groupprojects fields without grouping
category and count the number of documents in each group?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]
_id for group key and $sum: 1 to count [OK]- Using field name instead of
_idfor grouping key - Using
$countinstead of$sumfor counting - Using
$addwhich is not an accumulator
{ "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" } } }]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]
_id key field [OK]- Expecting separate documents without grouping
- Summing incorrectly or ignoring grouping
- Using
_id: nullwhich groups all documents together
{ $group: { category: "$category", total: { $sum: "$amount" } } }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]
_id in $group stage [OK]- Omitting the
_idfield - Confusing field names with grouping key
- Thinking
$sumneeds special syntax
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?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]
$match on aggregated fields [OK]- Filtering before grouping which filters documents, not groups
- Filtering on
_idinstead of aggregated field - Using
$sortinstead of filtering
Ready to prove it?
Pass the test and this pattern moves unknown
