Computed pattern for pre-aggregation in MongoDB - Time & Space Complexity
When we use computed patterns for pre-aggregation in MongoDB, we want to know how the work grows as data grows.
We ask: How does the time to compute aggregated results change when more data is added?
Analyze the time complexity of the following MongoDB aggregation pipeline.
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$customerId", totalSpent: { $sum: "$amount" } } },
{ $project: { customerId: "$_id", totalSpent: 1, _id: 0 } }
])
This pipeline filters completed orders, groups them by customer, and sums the amount spent per customer.
Look for repeated work inside the pipeline.
- Primary operation: Scanning each order document once to filter and group.
- How many times: Once per document in the orders collection.
As the number of orders grows, the pipeline processes each order once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 document checks and group updates |
| 100 | About 100 document checks and group updates |
| 1000 | About 1000 document checks and group updates |
Pattern observation: The work grows roughly in direct proportion to the number of orders.
Time Complexity: O(n)
This means the time to compute the aggregation grows linearly with the number of input documents.
[X] Wrong: "Grouping by customer means the time depends on the number of customers only."
[OK] Correct: The pipeline must still scan every order document to group them, so time depends on total orders, not just customers.
Understanding how aggregation scales helps you explain data processing costs clearly and shows you can reason about real database workloads.
"What if we added an index on the status field used in $match? How would that affect the time complexity?"
Practice
Solution
Step 1: Understand pre-aggregation concept
Pre-aggregation means computing summary data before queries run, so queries are faster.Step 2: Identify the main goal
The goal is to store computed summaries to avoid recalculating on every query.Final Answer:
To calculate and store summary data ahead of time for faster queries -> Option CQuick Check:
Pre-aggregation = faster queries [OK]
- Confusing pre-aggregation with data deletion
- Thinking it automatically creates indexes
- Mixing it with data replication
Solution
Step 1: Recall aggregation stages
$group is used to group documents and compute summary values like sums or counts.Step 2: Identify correct stage for pre-aggregation
Pre-aggregation requires grouping and computing, so $group is the right stage.Final Answer:
$group -> Option BQuick Check:
$group = grouping and computing summaries [OK]
- Choosing $match which filters but does not compute
- Confusing $project with grouping
- Selecting $sort which only orders data
[{ $group: { _id: "$category", total: { $sum: "$amount" } } }]
Assuming the collection has documents: {category: "A", amount: 10}, {category: "B", amount: 5}, {category: "A", amount: 15}.Solution
Step 1: Group documents by category
Documents with category "A" are grouped together, and category "B" separately.Step 2: Sum amounts per group
For "A": 10 + 15 = 25; for "B": 5.Final Answer:
[{_id: "A", total: 25}, {_id: "B", total: 5}] -> Option DQuick Check:
Sum amounts by category = correct totals [OK]
- Not grouping sums correctly
- Returning individual documents instead of grouped
- Using null _id which sums all documents
[{ $group: { _id: "$category", total: { $sum: "amount" } } }]Solution
Step 1: Check $sum operator syntax
$sum requires a field path starting with $, but "amount" is missing the $.Step 2: Confirm correct syntax
It should be $sum: "$amount" to sum the amount field values.Final Answer:
Missing $ before amount in $sum operator -> Option AQuick Check:
$sum needs $field syntax [OK]
- Forgetting $ before field names in operators
- Assuming $match is mandatory before $group
- Misusing _id field in $group
Solution
Step 1: Group by month and category correctly
Use $month operator on "$date" to extract month, and include "$category" as second key.Step 2: Compute total sales and average price correctly
Sum the "$amount" field for totalSales and average the "$price" field for avgPrice.Final Answer:
[{ $group: { _id: { month: { $month: "$date" }, category: "$category" }, totalSales: { $sum: "$amount" }, avgPrice: { $avg: "$price" } } }] -> Option AQuick Check:
Group by month+category, sum amount, avg price [OK]
- Grouping by full date instead of month
- Swapping sum and avg fields
- Not using $month operator for month extraction
Ready to prove it?
Pass the test and this pattern moves unknown
