- 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
How to calculate sum in MongoDB with aggregate()?
To get the sum, use $sum along with aggregate(). Let us create a collection with documents −
> db.demo337.insertOne({"Amount":100}); { "acknowledged" : true, "insertedId" : ObjectId("5e5231e5f8647eb59e56209b") } > db.demo337.insertOne({"Amount":500}); { "acknowledged" : true, "insertedId" : ObjectId("5e5231e9f8647eb59e56209c") } > db.demo337.insertOne({"Amount":400}); { "acknowledged" : true, "insertedId" : ObjectId("5e5231ebf8647eb59e56209d") }
Display all documents from a collection with the help of find() method −
> db.demo337.find();
This will produce the following output −
{ "_id" : ObjectId("5e5231e5f8647eb59e56209b"), "Amount" : 100 } { "_id" : ObjectId("5e5231e9f8647eb59e56209c"), "Amount" : 500 } { "_id" : ObjectId("5e5231ebf8647eb59e56209d"), "Amount" : 400 }
Following is the query to calculate sum in MongoDB −
> db.demo337.aggregate( ... [ ... { ... $group: ... { ... _id:null, ... totalAmount: { $sum:"$Amount" } ... } ... } ... ] ... );
This will produce the following output −
{ "_id" : null, "totalAmount" : 1000 }
Advertisements