How to 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 }

Updated on: 30-Jul-2019

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements