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 }
Updated on: 2019-07-30T22:30:26+05:30

214 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements