MongoDB aggregation / math operation to sum score of a specific student


To sum, use aggregate() along with $sum. Let us create a collection with documents −

> db.demo434.insertOne({"Name":"Chris","Score":45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e771603bbc41e36cc3cae93")
}
> db.demo434.insertOne({"Name":"David","Score":55});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e77161abbc41e36cc3cae94")
}
> db.demo434.insertOne({"Name":"Chris","Score":55});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e771624bbc41e36cc3cae95")
}

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

> db.demo434.find();

This will produce the following output −

{ "_id" : ObjectId("5e771603bbc41e36cc3cae93"), "Name" : "Chris", "Score" : 45 }
{ "_id" : ObjectId("5e77161abbc41e36cc3cae94"), "Name" : "David", "Score" : 55 }
{ "_id" : ObjectId("5e771624bbc41e36cc3cae95"), "Name" : "Chris", "Score" : 55 }

Following is the query tom sum score of a specific student −

> db.demo434.aggregate([
...    { "$match": { "Name": "Chris"} },
...    { "$group": { "_id": null, "TotalScore": { "$sum": "$Score" } } }
... ]);

This will produce the following output −

{ "_id" : null, "TotalScore" : 100 }

Updated on: 03-Apr-2020

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements