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 MongoDB Sub-documents field?
You can use aggregate framework for this. Let us first create a collection with documents −
> db.summingSubDocumentDemo.insertOne(
... { "_id" :101, "CustomerDetails" : { "CustomerPurchase" : { "CustomerPurchaseAmount" : 2000 } } });
{ "acknowledged" : true, "insertedId" : 101 }
> db.summingSubDocumentDemo.insertOne( { "_id" :102, "CustomerDetails" : { "CustomerPurchase" : { "CustomerPurchaseAmount" : 3000 } } });
{ "acknowledged" : true, "insertedId" : 102 }
> db.summingSubDocumentDemo.insertOne( { "_id" :103, "CustomerDetails" : { "CustomerPurchase" : { "CustomerPurchaseAmount" : 5000 } } });
{ "acknowledged" : true, "insertedId" : 103 }
Following is the query to display all documents from a collection with the help of find() method −
> db.summingSubDocumentDemo.find().pretty();
This will produce the following output −
{
"_id" : 101,
"CustomerDetails" : {
"CustomerPurchase" : {
"CustomerPurchaseAmount" : 2000
}
}
}
{
"_id" : 102,
"CustomerDetails" : {
"CustomerPurchase" : {
"CustomerPurchaseAmount" : 3000
}
}
}
{
"_id" : 103,
"CustomerDetails" : {
"CustomerPurchase" : {
"CustomerPurchaseAmount" : 5000
}
}
}
Here is the query to sum MongoDB sub-documents fields −
> db.summingSubDocumentDemo.aggregate({$group : {_id: "",
... totalAmount : {$sum: "$CustomerDetails.CustomerPurchase.CustomerPurchaseAmount"}}},
... {$project: {_id: 0, totalAmount: 1}});
This will produce the following output −
{ "totalAmount" : 10000 }Advertisements