What if you could get the average of thousands of numbers instantly and perfectly every time?
Why $avg accumulator in MongoDB? - Purpose & Use Cases
Imagine you have a huge list of student test scores written on paper. You want to find the average score to see how the class did overall.
You start adding each score one by one and then divide by the total number of students.
This manual method is slow and tiring. You might miscount or add wrong numbers. If the list changes, you have to start over. It's easy to make mistakes and hard to keep track.
The $avg accumulator in MongoDB automatically calculates the average of values in your data. It does the math quickly and correctly, even if your data changes or grows.
let total = 0; for (let score of scores) { total += score; } let average = total / scores.length;
db.collection.aggregate([
{ $group: { _id: null, averageScore: { $avg: "$score" } } }
])It lets you quickly find averages from large or changing data sets without errors or extra work.
A teacher uses $avg to find the average test score of a class from thousands of student records stored in a database, instantly seeing how well the class performed.
Manually calculating averages is slow and error-prone.
$avg automates average calculation in MongoDB queries.
This saves time and ensures accurate results on big or changing data.
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
