Sum MongoDB Sub-documents field?

MongoDBDatabaseBig Data Analytics

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 }
raja
Published on 23-May-2019 12:10:37
Advertisements