MongoDB aggregation to sum individual properties on an object in an array across documents



For this, use aggregate() in MongoDB. Let us first create a collection with documents −

> db.demo131.insertOne( ...    { ...       "_id": 101, ...       "Details": [ ...          { ...             "PlayerScore": 500, ...             "PlayerName": "Chris" ...          }, ...          { ...             "PlayerScore": 400, ...             "PlayerName": "David" ...          } ...       ] ...    } ... ); { "acknowledged" : true, "insertedId" : 101 } > db.demo131.insertOne( ...    { ...       "_id": 102, ...       "Details": [ ...          { ...             "PlayerScore": 600, ...             "PlayerName": "Chris" ...          }, ...          { ...             "PlayerScore": 200, ...             "PlayerName": "David" ...          } ...       ] ...    } ... ); { "acknowledged" : true, "insertedId" : 102 }

Display all documents from a collection with the help of find() method −

> db.demo131.find();

This will produce the following output −

{ "_id" : 101, "Details" : [ { "PlayerScore" : 500, "PlayerName" : "Chris" }, { "PlayerScore" : 400, "PlayerName" : "David" } ] } { "_id" : 102, "Details" : [ { "PlayerScore" : 600, "PlayerName" : "Chris" }, { "PlayerScore" : 200, "PlayerName" : "David" } ] }

Following is the query to sum individual properties on an object in an array −

> db.demo131.aggregate([ ...    { $unwind: "$Details" }, ...    { ...       $group: { ...          _id:"$Details.PlayerName", ...          Value:{$sum:"$Details.PlayerScore"} ...       } ...    }, ... { ...    $group: { ...       _id: 0, ...       Details:{ $push: {Details:"$_id",Value:"$Value"}} ...       } ...    }, ... { ...    $project:{Details:1,_id:0} ... } ])

This will produce the following output −

{ "Details" : [ { "Details" : "David", "Value" : 600 }, { "Details" : "Chris", "Value" : 1100 } ] }
Updated on: 2020-03-31T11:57:03+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements