
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
Sum Every Field in a Sub-Document of MongoDB
To sum every field in a sub document, use aggregate framework. Let us first create a collection with documents −
> db.sumEveryFieldDemo.insertOne( ... { ... "_id":101, ... "PlayerDetails": [ ... {"PlayerName":"John","PlayerScore":1000}, ... {"PlayerName":"Carol","PlayerScore":2000}, ... {"PlayerName":"Sam","PlayerScore":3000} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
Following is the query to display all documents from a collection with the help of find() method −
> db.sumEveryFieldDemo.find().pretty();
This will produce the following output −
{ "_id" : 101, "PlayerDetails" : [ { "PlayerName" : "John", "PlayerScore" : 1000 }, { "PlayerName" : "Carol", "PlayerScore" : 2000 }, { "PlayerName" : "Sam", "PlayerScore" : 3000 } ] }
Following is the query to sum every field in a sub document of MongoDB −
> db.sumEveryFieldDemo.aggregate( [ ... { $unwind: "$PlayerDetails" }, ... { $group: { ... _id: '$_id', ... sum: { $sum: '$PlayerDetails.PlayerScore' } ... } } ... ] ).pretty();
This will produce the following output −
{ "_id" : 101, "sum" : 6000 }
Advertisements