Is it possible to sum two fields in MongoDB using the Aggregation framework?

Yes, it is possible to sum two fields in MongoDB using the $add operator within the $project stage of the aggregation framework. This creates a new computed field containing the sum of existing fields.

Syntax

db.collection.aggregate([
    {
        $project: {
            field1: "$field1",
            field2: "$field2",
            sumField: { $add: ["$field1", "$field2"] }
        }
    }
]);

Sample Data

db.sumTwoFieldsDemo.insertMany([
    {"FirstValue": 150, "SecondValue": 350},
    {"FirstValue": 450, "SecondValue": 1550},
    {"FirstValue": 2560, "SecondValue": 2440}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c9b4bfe15e86fd1496b38cd"),
        ObjectId("5c9b4c1215e86fd1496b38ce"),
        ObjectId("5c9b4c2715e86fd1496b38cf")
    ]
}

Display Sample Data

db.sumTwoFieldsDemo.find();
{
    "_id": ObjectId("5c9b4bfe15e86fd1496b38cd"),
    "FirstValue": 150,
    "SecondValue": 350
}
{
    "_id": ObjectId("5c9b4c1215e86fd1496b38ce"),
    "FirstValue": 450,
    "SecondValue": 1550
}
{
    "_id": ObjectId("5c9b4c2715e86fd1496b38cf"),
    "FirstValue": 2560,
    "SecondValue": 2440
}

Example: Sum Two Fields Using $project

db.sumTwoFieldsDemo.aggregate([
    {
        $project: {
            "First": "$FirstValue",
            "Second": "$SecondValue",
            "TotalValueOfBothFields": { $add: ["$FirstValue", "$SecondValue"] }
        }
    }
]);
{ "_id": ObjectId("5c9b4bfe15e86fd1496b38cd"), "First": 150, "Second": 350, "TotalValueOfBothFields": 500 }
{ "_id": ObjectId("5c9b4c1215e86fd1496b38ce"), "First": 450, "Second": 1550, "TotalValueOfBothFields": 2000 }
{ "_id": ObjectId("5c9b4c2715e86fd1496b38cf"), "First": 2560, "Second": 2440, "TotalValueOfBothFields": 5000 }

Key Points

  • The $add operator accepts an array of field references or numeric values
  • Use $project stage to include original fields and computed sum field in results
  • Field references must be prefixed with $ symbol (e.g., "$FirstValue")

Conclusion

The MongoDB aggregation framework makes it easy to sum multiple fields using the $add operator within a $project stage. This approach creates computed fields without modifying the original document structure.

Updated on: 2026-03-15T00:31:43+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements