MongoDB - How to get the sum of two columns and save it to another column?

To get the sum of two columns and save it to another column in MongoDB, use the $add operator within an aggregation pipeline with the $project stage.

Syntax

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

Sample Data

Let us create a collection with sample documents ?

db.demo291.insertOne({"Value1": 10, "Value2": 50});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e4c0e1e5d93261e4bc9ea2f")
}

Display all documents from the collection ?

db.demo291.find();
{ "_id": ObjectId("5e4c0e1e5d93261e4bc9ea2f"), "Value1": 10, "Value2": 50 }

Example: Sum Two Columns

Get the sum of Value1 and Value2, and save it to a new column "Value3" ?

db.demo291.aggregate([
    {
        $project: {
            "Value1": "$Value1",
            "Value2": "$Value2",
            "Value3": { $add: ["$Value1", "$Value2"] }
        }
    }
]);
{ "_id": ObjectId("5e4c0e1e5d93261e4bc9ea2f"), "Value1": 10, "Value2": 50, "Value3": 60 }

Key Points

  • The $add operator takes an array of numeric fields to sum
  • Use $project to include original fields and the computed sum
  • Field references require the $ prefix (e.g., "$Value1")

Conclusion

Use MongoDB's $add operator within an aggregation pipeline to sum multiple columns and project the result as a new field. This approach allows you to perform calculations while preserving original data.

Updated on: 2026-03-15T02:19:06+05:30

641 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements