0
0
MongoDBquery~5 mins

$avg accumulator in MongoDB

Choose your learning style9 modes available
Introduction

The $avg accumulator helps you find the average value of numbers in a group. It makes it easy to calculate the mean without doing math yourself.

You want to find the average score of students in a class.
You need to calculate the average price of products in a category.
You want to know the average rating of movies in a collection.
You want to find the average temperature recorded each day.
You want to calculate the average sales amount per salesperson.
Syntax
MongoDB
{ $avg: <expression> }

The <expression> is usually a field name that holds numbers.

You use $avg inside aggregation stages like $group.

Examples
Calculate the average of the score field values.
MongoDB
{ $avg: "$score" }
Calculate the average of the price field and the number 10.
MongoDB
{ $avg: [ "$price", 10 ] }
Sample Program

This query groups students by their class and calculates the average score for each class.

MongoDB
db.students.aggregate([
  {
    $group: {
      _id: "$class",
      averageScore: { $avg: "$score" }
    }
  }
])
OutputSuccess
Important Notes

If the field has no numeric values, $avg returns null.

You can use $avg with arrays by passing an array of expressions.

Summary

$avg calculates the average of numeric values in a group.

It is used inside aggregation pipelines, mostly with $group.

It helps quickly find mean values without manual calculations.