Find sum of fields inside array in MongoDB?

MongoDBDatabaseBig Data Analytics

To find sum of fields inside array, use $sum. Let us create a collection with documents −

> db.demo96.insertOne(
... {
...
...    "Name" : "Chris",
...    "Details" : [
...       {
...          Marks:67
...       },
...       {
...          Marks:33
...       },
...       {
...          Marks:50
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2d6aadb8903cdd865577ad")
}

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

> db.demo96.find();

This will produce the following output −

{
   "_id" : ObjectId("5e2d6aadb8903cdd865577ad"), "Name" : "Chris", "Details" : [
      { "Marks" : 67 }, { "Marks" : 33 }, { "Marks" : 50 }
   ] 
}

Following is the query to find sum of fields inside array in MongoDB −

> db.demo96.aggregate([
... { "$project": {
...    "Name": 1,
...    "TotalMarks": {
...       "$sum": "$Details.Marks"
...       }
...    }}
... ]);

This will produce the following output −

{ "_id" : ObjectId("5e2d6aadb8903cdd865577ad"), "Name" : "Chris", "TotalMarks" : 150 }
raja
Published on 30-Mar-2020 14:25:47
Advertisements