Calculate the average value in a MongoDB document grouping by null?

To calculate the average value across all documents in a MongoDB collection, use the $group operator with _id: null to group all documents together, then apply the $avg accumulator operator.

Syntax

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

Sample Data

Let us create a collection with population documents ?

db.calculateAverageDemo.insertMany([
    { "Population": 100 },
    { "Population": 500 },
    { "Population": 200 },
    { "Population": 100 },
    { "Population": 100 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("...")
    ]
}

Display Documents

db.calculateAverageDemo.find();
{ "_id": ObjectId("5cd68a197924bb85b3f4895f"), "Population": 100 }
{ "_id": ObjectId("5cd68a1c7924bb85b3f48960"), "Population": 500 }
{ "_id": ObjectId("5cd68a237924bb85b3f48961"), "Population": 200 }
{ "_id": ObjectId("5cd68a297924bb85b3f48962"), "Population": 100 }
{ "_id": ObjectId("5cd68a2e7924bb85b3f48963"), "Population": 100 }

Calculate Average

Calculate the average population across all documents ?

db.calculateAverageDemo.aggregate([
    {
        $group: {
            _id: null,
            "AveragePopulation": { $avg: "$Population" }
        }
    }
]);
{ "_id": null, "AveragePopulation": 200 }

How It Works

  • _id: null groups all documents into a single group
  • $avg: "$Population" calculates the arithmetic mean of the Population field
  • The result shows the average value: (100 + 500 + 200 + 100 + 100) ÷ 5 = 200

Conclusion

Use $group with _id: null and $avg to calculate the average value across all documents in a MongoDB collection. This approach treats the entire collection as one group for aggregation.

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

379 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements