- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 }
- Related Articles
- How to aggregate sum in MongoDB to get the total count?
- How to calculate sum of string in MongoDB?
- How to get only values in arrays with MongoDB aggregate?
- To Aggregate Totals in One Group with MongoDB
- How to update after aggregate in MongoDB?
- How to aggregate array documents in MongoDB?
- How to use MongoDB Aggregate to sort?
- Aggregate based on array value to sum values in different MongoDB documents?
- Calculate frequency of duplicate names from NAME field using MongoDB aggregate?
- How to calculate timestamp difference in hours with MongoDB?
- MongoDB aggregate query to sort
- Sum with MongoDB group by multiple columns to calculate total marks with duplicate ids
- Get the average of marks in MongoDB with aggregate?
- How to calculate a sum of specific documents using MongoDB aggregation?
- Get substring in MongoDB aggregate

Advertisements