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


Yes, it is possible using the $project operator. Let us first create a collection with documents

> db.sumTwoFieldsDemo.insertOne({"FirstValue":150,"SecondValue":350});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b4bfe15e86fd1496b38cd")
}
> db.sumTwoFieldsDemo.insertOne({"FirstValue":450,"SecondValue":1550});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b4c1215e86fd1496b38ce")
}
> db.sumTwoFieldsDemo.insertOne({"FirstValue":2560,"SecondValue":2440});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b4c2715e86fd1496b38cf")
}

Following is the query to display all documents from a collection with the help of find() method

> db.sumTwoFieldsDemo.find().pretty();

This will produce the following output

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

Following is the query to sum 2 fields in MongoDB using the $project operator

> db.sumTwoFieldsDemo.aggregate(
...    { "$project" :
...       {
...          'First' : '$FirstValue',
...          'Second' : '$SecondValue',
...          'TotalValueOfBothFields' : { '$add' : [ '$FirstValue', '$SecondValue' ] },
...       }
...    }
... );

This will produce the following output

{ "_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 }

Updated on: 30-Jul-2019

960 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements