How to calculate sum in MongoDB with aggregate()?

To calculate sum in MongoDB, use the $sum operator along with the aggregate() method. The $sum operator is used within a $group stage to calculate the total of numeric field values across documents.

Syntax

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

Create Sample Data

Let us create a collection with documents having Amount field ?

db.demo337.insertMany([
    {"Amount": 100},
    {"Amount": 500},
    {"Amount": 400}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e5231e5f8647eb59e56209b"),
        ObjectId("5e5231e9f8647eb59e56209c"),
        ObjectId("5e5231ebf8647eb59e56209d")
    ]
}

Display Sample Data

db.demo337.find();
{ "_id": ObjectId("5e5231e5f8647eb59e56209b"), "Amount": 100 }
{ "_id": ObjectId("5e5231e9f8647eb59e56209c"), "Amount": 500 }
{ "_id": ObjectId("5e5231ebf8647eb59e56209d"), "Amount": 400 }

Example: Calculate Sum of Amount Field

Following is the query to calculate sum using aggregate() ?

db.demo337.aggregate([
    {
        $group: {
            _id: null,
            totalAmount: { $sum: "$Amount" }
        }
    }
]);
{ "_id": null, "totalAmount": 1000 }

How It Works

  • The $group stage groups all documents together using _id: null
  • $sum: "$Amount" adds up all Amount field values from the grouped documents
  • The result shows the calculated total in the totalAmount field

Conclusion

Use $sum within $group stage of aggregate() to calculate sum of numeric fields. Set _id: null to group all documents together for a total sum calculation.

Updated on: 2026-03-15T02:32:29+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements