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 }