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