
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Calculate Sum of Specific Documents Using MongoDB Aggregation
To sum, use $sum and to get sum of specific documents, you need to group them using $group in MongoDB.
Let us first create a collection with documents −
>db.calculateSumOfDocument.insertOne({"ListOfUsers":["Carol","Bob"],"UsersDetails":[{"FirstUser":"Carol","TotalLikes":20},{"FirstUser":"Bob","TotalLikes":45}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e084e9125ddae1f53b6220c") } >db.calculateSumOfDocument.insertOne({"ListOfUsers":["Carol","Bob"],"UsersDetails":[{"FirstUser":"Carol","TotalLikes":60},{"FirstUser":"Bob","TotalLikes":50}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e084f6125ddae1f53b6220d") }
Following is the query to display all documents from a collection with the help of find() method −
> db.calculateSumOfDocument.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e084e9125ddae1f53b6220c"), "ListOfUsers" : [ "Carol", "Bob" ], "UsersDetails" : [ { "FirstUser" : "Carol", "TotalLikes" : 20 }, { "FirstUser" : "Bob", "TotalLikes" : 45 } ] } { "_id" : ObjectId("5e084f6125ddae1f53b6220d"), "ListOfUsers" : [ "Carol", "Bob" ], "UsersDetails" : [ { "FirstUser" : "Carol", "TotalLikes" : 60 }, { "FirstUser" : "Bob", "TotalLikes" : 50 } ] }
Following is the query to calculate sum of specific documents using aggregation −
> db.calculateSumOfDocument.aggregate([ ... { ... "$match": { "UsersDetails.FirstUser": "Carol" } ... }, ... { "$unwind" : "$UsersDetails" }, ... { ... "$match": { "UsersDetails.FirstUser": "Carol" } ... }, ... { ... "$group": { ... "_id": null, ... "total": { "$sum": "$UsersDetails.TotalLikes" } ... } ... } ... ]);
This will produce the following output −
{ "_id" : null, "total" : 80 }
Advertisements