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


To get the sum of two columns, use $add. Let us create a collection with documents −

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

Display all documents from a collection with the help of find() method −

> db.demo291.find();

This will produce the following output −

{ "_id" : ObjectId("5e4c0e1e5d93261e4bc9ea2f"), "Value1" : 10, "Value2" : 50 }

Following is the query to get the sum of two columns and save it to another column “Value3” −

> db.demo291.aggregate(
...   { "$project" : {
...      'Value1' : '$Value1',
...      'Value2' : '$Value2',
...      'Value3' : { '$add' : [ '$Value1', '$Value2' ] }
...   }
...   }
...);

This will produce the following output −

{ "_id" : ObjectId("5e4c0e1e5d93261e4bc9ea2f"), "Value1" : 10, "Value2" : 50, "Value3" : 60 }

Updated on: 31-Mar-2020

486 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements