- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
Advertisements