MongoDB query to add up the values of a specific field in documents

To add up the values of a specific field across all documents in MongoDB, use the $sum aggregation operator within a $group stage. This calculates the total sum of numeric field values.

Syntax

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

Create Sample Data

Let us create a collection with sample documents ?

db.demo677.insertMany([
    { Value: 10 },
    { Value: 50 },
    { Value: 20 },
    { Value: 20 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5ea421f404263e90dac943f8"),
        ObjectId("5ea421f704263e90dac943f9"),
        ObjectId("5ea421fa04263e90dac943fa"),
        ObjectId("5ea421fe04263e90dac943fb")
    ]
}

Display All Documents

db.demo677.find();
{ "_id": ObjectId("5ea421f404263e90dac943f8"), "Value": 10 }
{ "_id": ObjectId("5ea421f704263e90dac943f9"), "Value": 50 }
{ "_id": ObjectId("5ea421fa04263e90dac943fa"), "Value": 20 }
{ "_id": ObjectId("5ea421fe04263e90dac943fb"), "Value": 20 }

Example: Sum All Values

Calculate the total sum of all Value fields across documents ?

db.demo677.aggregate([
    { $group: { _id: null, sum: { $sum: "$Value" } } }
]);
{ "_id": null, "sum": 100 }

Key Points

  • _id: null groups all documents together into a single group
  • $sum: "$Value" adds up all values from the Value field
  • The $ prefix indicates a field reference in aggregation

Conclusion

Use $group with $sum to calculate field totals in MongoDB. Setting _id: null groups all documents together, while $sum: "$fieldName" performs the addition operation.

Updated on: 2026-03-15T03:28:25+05:30

321 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements