Calculating average value per document with sort in MongoDB?

To calculate the average value per document in MongoDB, use the aggregation framework with $addFields and $avg operators. You can combine this with $sort to order results by the calculated average.

Syntax

db.collection.aggregate([
    { $addFields: { "avgField": { $avg: "$arrayField" } } },
    { $sort: { "avgField": 1 } }
]);

Sample Data

db.calculateAverage.insertMany([
    { "Value": [10, 20, 80] },
    { "Value": [12, 15, 16] },
    { "Value": [30, 35, 40] }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e0383e3f5e889d7a51994dc"),
        ObjectId("5e0383edf5e889d7a51994dd"), 
        ObjectId("5e0383f5f5e889d7a51994de")
    ]
}

View Sample Data

db.calculateAverage.find();
{
    "_id": ObjectId("5e0383e3f5e889d7a51994dc"),
    "Value": [10, 20, 80]
}
{
    "_id": ObjectId("5e0383edf5e889d7a51994dd"),
    "Value": [12, 15, 16]
}
{
    "_id": ObjectId("5e0383f5f5e889d7a51994de"),
    "Value": [30, 35, 40]
}

Calculate Average with Sort

Calculate the average of each document's Value array and sort by ascending average ?

db.calculateAverage.aggregate([
    { $addFields: { "calavg": { $avg: "$Value" } } },
    { $sort: { "calavg": 1 } }
]);
{ "_id": ObjectId("5e0383edf5e889d7a51994dd"), "Value": [12, 15, 16], "calavg": 14.333333333333334 }
{ "_id": ObjectId("5e0383f5f5e889d7a51994de"), "Value": [30, 35, 40], "calavg": 35 }
{ "_id": ObjectId("5e0383e3f5e889d7a51994dc"), "Value": [10, 20, 80], "calavg": 36.666666666666664 }

Sort by Descending Average

db.calculateAverage.aggregate([
    { $addFields: { "calavg": { $avg: "$Value" } } },
    { $sort: { "calavg": -1 } }
]);

Key Points

  • $addFields adds a new field without replacing existing document structure.
  • $avg calculates the arithmetic mean of array elements per document.
  • $sort with value 1 sorts ascending, -1 sorts descending.

Conclusion

Use $addFields with $avg to calculate per-document averages from arrays, then apply $sort to order results by the computed average values in your desired sequence.

Updated on: 2026-03-15T01:45:53+05:30

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements