Introduction to MongoDB $avg Operator

The MongoDB $avg aggregation pipeline operator is used to calculate the average value of a specific field. This operator can only be used within an aggregation pipeline.

Syntax

The syntax of the MongoDB $avg operator is as follows:

{
  $avg: "<field>"
}

Here, <field> is the name of the field whose average value is to be calculated, and it can be any valid field name.

Use Cases

The MongoDB $avg operator is commonly used in the following scenarios:

  • Calculating the average value of a specific field
  • Calculating data for statistical analysis

Examples

Here are a few examples of using the $avg operator.

Example 1

Suppose we have the following data:

{ "name": "Alice", "age": 20 }
{ "name": "Bob", "age": 30 }
{ "name": "Charlie", "age": 25 }
{ "name": "David", "age": 35 }
{ "name": "Eva", "age": 28 }

To calculate the average value of the age field, we can use the following aggregation pipeline:

db.people.aggregate([{ $group: { _id: null, averageAge: { $avg: "$age" } } }])

Executing the above pipeline will return the following result:

{ "_id" : null, "averageAge" : 27.6 }

Example 2

Suppose we have the following data:

{ "name": "Alice", "age": 20, "score": 85 }
{ "name": "Bob", "age": 30, "score": 90 }
{ "name": "Charlie", "age": 25, "score": 80 }
{ "name": "David", "age": 35, "score": 95 }
{ "name": "Eva", "age": 28, "score": 87 }

To calculate the average value of the score field, we can use the following aggregation pipeline:

db.people.aggregate([
  { $group: { _id: null, averageScore: { $avg: "$score" } } }
])

Executing the above pipeline will return the following result:

{ "_id" : null, "averageScore" : 87.4 }

Example 3

Suppose we have the following data:

{ "name": "Alice", "age": 20, "score": 85, "subject": "math" }
{ "name": "Bob", "age": 30, "score": 90, "subject": "math" }
{ "name": "Charlie", "age": 25, "score": 80, "subject": "history" }
{ "name": "David", "age": 35, "score": 95, "subject": "math" }
{ "name": "Eva", "age": 28, "score": 87, "subject": "history" }

To calculate the average value of the score field for each subject, we can use the following aggregation pipeline:

db.people.aggregate([
  { $group: { _id: "$subject", averageScore: { $avg: "$score" } } }
])

Executing the above pipeline will return the following result:

{ "_id" : "history", "averageScore" : 83.5 }
{ "_id" : "math", "averageScore" : 90 }

Conclusion

The $avg aggregation operator in MongoDB is used to calculate the average value of a specified field in a collection. This operator is commonly used for data analysis and statistics. In practical applications, it can be combined with other operators for more complex data processing and analysis.