MongoDB query to get average in aggregation of array element?

To calculate the average of array elements in MongoDB, use the $avg operator in an aggregation pipeline. This operator computes the arithmetic mean of all numeric values in an array field.

Syntax

db.collection.aggregate([
    { $project: { fieldName: { $avg: "$arrayField" } } }
])

Sample Data

Let us create a collection with documents containing an array of marks ?

db.demo584.insertOne({
    "Marks": [75, 50, 85, 60, 80]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e91d827fd2d90c177b5bcc2")
}

Display all documents from the collection ?

db.demo584.find().pretty();
{
    "_id": ObjectId("5e91d827fd2d90c177b5bcc2"),
    "Marks": [
        75,
        50,
        85,
        60,
        80
    ]
}

Example

Calculate the average of array elements using aggregation ?

db.demo584.aggregate([
    { $project: { MarksAvg: { $avg: "$Marks" } } }
]);
{ "_id": ObjectId("5e91d827fd2d90c177b5bcc2"), "MarksAvg": 70 }

Key Points

  • The $avg operator calculates the arithmetic mean of numeric array elements
  • Non-numeric values in the array are ignored during calculation
  • Use $project stage to create a new field containing the average value

Conclusion

The $avg operator in MongoDB aggregation pipelines efficiently calculates the average of array elements. It automatically handles numeric conversion and ignores non-numeric values, making it ideal for statistical calculations on array data.

Updated on: 2026-03-15T03:45:03+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements