MongoDB query to calculate average

To calculate the average of numeric values in MongoDB, use the $avg aggregation operator within the $group stage. This operator computes the average of all specified numeric values across documents.

Syntax

db.collection.aggregate([
    {
        $group: {
            "_id": null,
            "averageField": { $avg: "$fieldName" }
        }
    }
]);

Sample Data

Let us create a collection with product price documents ?

db.demo80.insertMany([
    {"Details": {"Price": 10.5}},
    {"Details": {"Price": 50.3}},
    {"Details": {"Price": 100.10}}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e2bf43271bf0181ecc42297"),
        ObjectId("5e2bf43871bf0181ecc42298"),
        ObjectId("5e2bf43f71bf0181ecc42299")
    ]
}

Verify Sample Data

db.demo80.find();
{ "_id": ObjectId("5e2bf43271bf0181ecc42297"), "Details": { "Price": 10.5 } }
{ "_id": ObjectId("5e2bf43871bf0181ecc42298"), "Details": { "Price": 50.3 } }
{ "_id": ObjectId("5e2bf43f71bf0181ecc42299"), "Details": { "Price": 100.1 } }

Calculate Average Price

Use the $avg operator to calculate the average of all prices ?

db.demo80.aggregate([
    {
        $group: {
            "_id": null,
            "AvgValue": {
                "$avg": "$Details.Price"
            }
        }
    }
]);
{ "_id": null, "AvgValue": 53.633333333333326 }

Key Points

  • The $avg operator ignores non-numeric values and null values in calculations.
  • Setting "_id": null groups all documents together for a single average result.
  • Use dot notation like "$Details.Price" to access nested field values.

Conclusion

The $avg aggregation operator efficiently calculates averages of numeric fields across documents. Use it within $group stages to compute statistical summaries of your data collections.

Updated on: 2026-03-15T01:51:34+05:30

586 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements