Sum the score of duplicate column values in MongoDB documents?


To sum values in different documents, use MongoDB $group. Let us create a collection with documents −

> db.demo512.insertOne({"Name":"Chris","Score1":45,"Score2":65,"CountryName":"US"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e884d96987b6e0e9d18f588")
}
> db.demo512.insertOne({"Name":"Chris","Score1":41,"Score2":45,"CountryName":"US"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e884da2987b6e0e9d18f589")
}
> db.demo512.insertOne({"Name":"Bob","Score1":75,"Score2":55,"CountryName":"US"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e884db2987b6e0e9d18f58a")
}
> db.demo512.insertOne({"Name":"Bob","Score1":65,"Score2":90,"CountryName":"US"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e884dc2987b6e0e9d18f58b")
}

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

> db.demo512.find();

This will produce the following output −

{ "_id" : ObjectId("5e884d96987b6e0e9d18f588"), "Name" : "Chris", "Score1" : 45, "Score2" :
65, "CountryName" : "US" }
{ "_id" : ObjectId("5e884da2987b6e0e9d18f589"), "Name" : "Chris", "Score1" : 41, "Score2" :
45, "CountryName" : "US" }
{ "_id" : ObjectId("5e884db2987b6e0e9d18f58a"), "Name" : "Bob", "Score1" : 75, "Score2" :
55, "CountryName" : "US" }
{ "_id" : ObjectId("5e884dc2987b6e0e9d18f58b"), "Name" : "Bob", "Score1" : 65, "Score2" :
90, "CountryName" : "US" }

Following is the query to sum the score of duplicate column values in MongoDB −

> db.demo512.aggregate([
...    {
...       "$group": {
...          "_id": "$Name",
...          "Score1": { "$sum": "$Score1" },
...          "Score2": { "$sum": "$Score2" },
...          "CountryName": { "$first": "$CountryName" }
...       }
...    },
...    {
...       "$project": {
...          "_id": 0,
...          "Name": "$_id",
...          "Score1": 1,
...          "Score2": 1,
...          "CountryName": 1
...       }
...    },
...    { "$out": "demo513" }
... ])

Following is the query to display the result −

> db.demo513.find();

This will produce the following output −

{ "_id" : ObjectId("5e884f0e79442efd15c6eae0"), "Score1" : 140, "Score2" : 145, "CountryName" : "US", "Name" : "Bob" }
{ "_id" : ObjectId("5e884f0e79442efd15c6eae1"), "Score1" : 86, "Score2" : 110, "CountryName" : "US", "Name" : "Chris" }

Updated on: 13-May-2020

111 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements