Calculate average of ratings in array and then include the field to original document in MongoDB?

To calculate the average of ratings in an array and include this field in the original document in MongoDB, use the $addFields stage with $avg operator in an aggregation pipeline. This adds a computed field without modifying the original document structure.

Syntax

db.collection.aggregate([
    {
        $addFields: {
            averageField: { $avg: "$arrayField.numericField" }
        }
    }
]);

Sample Data

db.averageOfRatingsInArrayDemo.insertOne({
    "StudentDetails": [
        {
            "StudentId": 1,
            "StudentScore": 45
        },
        {
            "StudentId": 2,
            "StudentScore": 58
        },
        {
            "StudentId": 3,
            "StudentScore": 67
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cd427dc2cba06f46efe9ee4")
}

Example

Calculate the average of StudentScore values and add it as a new field to the document ?

db.averageOfRatingsInArrayDemo.aggregate([
    {
        $addFields: {
            StudentScoreAverage: { $avg: "$StudentDetails.StudentScore" }
        }
    }
]);
{
    "_id": ObjectId("5cd427dc2cba06f46efe9ee4"),
    "StudentDetails": [
        { "StudentId": 1, "StudentScore": 45 },
        { "StudentId": 2, "StudentScore": 58 },
        { "StudentId": 3, "StudentScore": 67 }
    ],
    "StudentScoreAverage": 56.666666666666664
}

How It Works

  • $addFields stage adds new computed fields to documents without removing existing fields.
  • $avg operator calculates the average of numeric values in the specified array field.
  • The dot notation "$StudentDetails.StudentScore" extracts all StudentScore values from the array.

Conclusion

Use $addFields with $avg in an aggregation pipeline to calculate array averages and include them as new fields. This preserves the original document structure while adding computed values.

Updated on: 2026-03-15T01:11:15+05:30

426 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements