0
0
MongoDBquery~30 mins

$avg accumulator in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Use db.students.aggregate(pipeline) to run the aggregation.