Find sum of fields inside array in MongoDB?



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 }
Updated on: 2020-03-30T10:56:46+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements