How to sum every field in a sub document of MongoDB?

MongoDBDatabaseBig Data Analytics

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 }
raja
Published on 21-May-2019 08:58:47
Advertisements