Calculate Average Scores Using $avg Accumulator in MongoDB
📖 Scenario: You are managing a small school's student test scores stored in a MongoDB collection. You want to find the average score of all students to understand overall performance.
🎯 Goal: Build a MongoDB aggregation query that uses the $avg accumulator to calculate the average score of all students in the collection.
📋 What You'll Learn
Create a collection named students with documents containing name and score fields.
Add a configuration variable scoreField to hold the field name score.
Write an aggregation pipeline that uses $group stage with $avg accumulator on the scoreField.
Complete the aggregation query to output the average score with the field name averageScore.
💡 Why This Matters
🌍 Real World
Calculating averages is common in reporting systems, such as finding average sales, test scores, or ratings stored in databases.
💼 Career
Understanding how to use MongoDB aggregation and accumulators like <code>$avg</code> is essential for data analysts and backend developers working with NoSQL databases.
Progress0 / 4 steps
1
Create the students collection with sample data
Create a MongoDB collection called students with these exact documents: { name: "Alice", score: 85 }, { name: "Bob", score: 90 }, and { name: "Charlie", score: 78 }.
MongoDB
Hint
Use db.students.insertMany([...]) to add multiple documents at once.
2
Add a configuration variable for the score field
Create a variable called scoreField and set it to the string "score" to represent the field name holding the scores.
MongoDB
Hint
Use const scoreField = "score" to store the field name.
3
Write the aggregation pipeline using $avg
Write a MongoDB aggregation pipeline called pipeline that uses a $group stage to calculate the average of the field stored in scoreField. Use $avg: "$" + scoreField to reference the field dynamically. Name the output field averageScore.
MongoDB
Hint
Use $group with _id: null to aggregate all documents together.
4
Complete the aggregation query to get the average score
Run the aggregation query on the students collection using the pipeline variable and assign the result to a variable called result.
MongoDB
Hint
Use db.students.aggregate(pipeline) to run the aggregation.
Practice
(1/5)
1. What does the $avg accumulator do in a MongoDB aggregation pipeline?
easy
A. Calculates the average value of numeric fields in grouped documents
B. Counts the total number of documents in a collection
C. Finds the maximum value in a group of documents
D. Sorts documents in ascending order
Solution
Step 1: Understand the purpose of $avg
The $avg accumulator 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 $count perform different tasks, so $avg specifically calculates averages.
Final Answer:
Calculates the average value of numeric fields in grouped documents -> Option A
Quick Check:
$avg = average calculation [OK]
Hint: Remember: $avg means average, not count or max [OK]
Common Mistakes:
Confusing $avg with $sum or $count
Thinking $avg sorts data
Assuming $avg works outside aggregation
2. Which of the following is the correct syntax to calculate the average of the field score in a MongoDB aggregation $group stage?