$avg accumulator in MongoDB - Time & Space Complexity
When using the $avg accumulator in MongoDB, it's important to understand how the time to calculate the average changes as the amount of data grows.
We want to know how the work done by $avg scales when more documents are processed.
Analyze the time complexity of the following MongoDB aggregation snippet.
db.sales.aggregate([
{ $group: { _id: "$store", averageSales: { $avg: "$amount" } } }
])
This groups sales by store and calculates the average sales amount for each store.
Look at what repeats as the data grows.
- Primary operation: Summing the
amountvalues for each document in a group. - How many times: Once for each document in the input collection.
As the number of documents increases, the amount of work to sum and count grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 sums and counts |
| 100 | 100 sums and counts |
| 1000 | 1000 sums and counts |
Pattern observation: The work grows in a straight line with the number of documents.
Time Complexity: O(n)
This means the time to calculate the average grows directly with the number of documents processed.
[X] Wrong: "Calculating an average is instant no matter how many documents there are."
[OK] Correct: Even though the average is just one number, MongoDB must look at every document's value to add them up and count them first.
Understanding how aggregation stages like $avg scale helps you explain performance in real projects and shows you think about data size impact clearly.
What if we added a $match stage before $group to filter documents? How would that affect the time complexity?
Practice
$avg accumulator do in a MongoDB aggregation pipeline?Solution
Step 1: Understand the purpose of
The$avg$avgaccumulator is designed to calculate the mean (average) of numeric values within grouped documents in an aggregation pipeline.Step 2: Compare with other accumulators
Other accumulators like$sum,$max, and$countperform different tasks, so$avgspecifically calculates averages.Final Answer:
Calculates the average value of numeric fields in grouped documents -> Option AQuick Check:
$avg= average calculation [OK]
- Confusing $avg with $sum or $count
- Thinking $avg sorts data
- Assuming $avg works outside aggregation
score in a MongoDB aggregation $group stage?Solution
Step 1: Identify the correct accumulator name
The correct MongoDB accumulator for average is$avg, not$averageoravg.Step 2: Check the syntax structure
The syntax requires the field name as a string with a $ prefix inside$avg, and the whole inside a$groupstage with an _id.Final Answer:
{ $group: { _id: null, avgScore: { $avg: "$score" } } } -> Option BQuick Check:
Correct syntax uses $avg with field string [OK]
- Using $average instead of $avg
- Omitting quotes around field name
- Using $sum instead of $avg
students with documents:{ "name": "Alice", "score": 80 }, { "name": "Bob", "score": 90 }, { "name": "Charlie", "score": 70 }What will be the output of this aggregation?
[{ $group: { _id: null, averageScore: { $avg: "$score" } } }]Solution
Step 1: Calculate the sum of scores
Sum = 80 + 90 + 70 = 240.Step 2: Calculate the average
Average = 240 / 3 = 80.Final Answer:
[{ "_id": null, "averageScore": 80 }] -> Option CQuick Check:
Average of 80, 90, 70 = 80 [OK]
- Using sum instead of average
- Picking minimum or maximum score
- Forgetting to divide by number of documents
[{ $group: { _id: "$class", avgScore: { $avg: score } } }]What is the error in this pipeline?
Solution
Step 1: Check the field reference inside $avg
The field name must be a string with a $ prefix, so it should be "$score", not score.Step 2: Validate other parts of the pipeline
Using "$class" as _id is valid, and $avg is allowed inside $group. $match is optional.Final Answer:
Field name 'score' should be a string with $ prefix: "$score" -> Option DQuick Check:
Field names in $avg need "$field" format [OK]
- Using unquoted field names inside $avg
- Thinking $match is mandatory before $group
- Believing _id cannot be a field name
sales with documents:{ "region": "North", "amount": 100 }, { "region": "South", "amount": 200 }, { "region": "North", "amount": 300 }, { "region": "South", "amount": 400 }Write an aggregation pipeline to find the average sales amount per region and identify the region with the highest average sales.
Solution
Step 1: Group by region and calculate average
Use$groupwith_id: "$region"and$avg: "$amount"to get average sales per region.Step 2: Sort descending by average and limit to top
Sort byavgAmountdescending (-1) to get highest average first, then limit to 1 document.Final Answer:
[{ $group: { _id: "$region", avgAmount: { $avg: "$amount" } } }, { $sort: { avgAmount: -1 } }, { $limit: 1 }] -> Option AQuick Check:
Group, sort descending, limit 1 = highest average [OK]
- Using $sum instead of $avg for average
- Sorting ascending to get highest average
- Not limiting results to top 1
Ready to prove it?
Pass the test and this pattern moves unknown
