- 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
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 }
Advertisements
To Continue Learning Please Login
Login with Google