0
0
MongodbHow-ToBeginner · 3 min read

How to Use $avg in Aggregation in MongoDB: Syntax and Examples

In MongoDB aggregation, use the $avg operator to calculate the average of numeric values in a group or array. It is typically used inside the $group stage to find the average of a field across documents. You can also use $avg to calculate the average of an array within documents.
📐

Syntax

The $avg operator is used inside aggregation pipeline stages like $group or $project. It calculates the average of numeric values.

  • In $group: { $avg: "$fieldName" } calculates the average of the specified field across grouped documents.
  • In $project: { $avg: ["$field1", "$field2", ...] } calculates the average of specified fields or expressions within a single document.
json
{
  $group: {
    _id: "$groupField",
    averageValue: { $avg: "$numericField" }
  }
}
💻

Example

This example shows how to calculate the average score of students grouped by their class using $avg inside a $group stage.

javascript
db.students.aggregate([
  {
    $group: {
      _id: "$class",
      averageScore: { $avg: "$score" }
    }
  }
])
Output
[ { "_id": "Math", "averageScore": 85 }, { "_id": "Science", "averageScore": 90 } ]
⚠️

Common Pitfalls

Common mistakes when using $avg include:

  • Using $avg outside aggregation stages like $group or $project where it is not valid.
  • Passing a non-numeric field or missing field, which results in null or incorrect averages.
  • Not grouping documents properly before using $avg, leading to unexpected results.
javascript
/* Wrong: Using $avg outside $group or $project */
db.collection.aggregate([
  { $match: { status: "active" } },
  { $avg: "$score" } // Invalid stage
])

/* Right: Use $avg inside $group */
db.collection.aggregate([
  {
    $group: {
      _id: null,
      averageScore: { $avg: "$score" }
    }
  }
])
📊

Quick Reference

UsageDescriptionExample
$avg in $groupCalculates average of a field across grouped documents{ $avg: "$fieldName" }
$avg in $projectCalculates average of multiple fields or expressions in one document{ $avg: ["$field1", "$field2"] }
Input typeNumeric values only; non-numeric are ignored or cause nullUse numeric fields
OutputReturns average as a numbere.g., 42.5

Key Takeaways

Use $avg inside $group or $project stages in MongoDB aggregation pipelines.
$avg calculates the average of numeric values from fields or arrays.
Ensure the fields used with $avg contain numeric data to avoid null results.
Group documents properly before applying $avg to get meaningful averages.
Avoid using $avg as a standalone stage; it must be part of an aggregation operator.