For this, use aggregate() along with $group. Let us create a collection with documents −
> db.demo627.insertOne({id:101,"Name":"Chris","Marks":54}); { "acknowledged" : true, "insertedId" : ObjectId("5e9acb306c954c74be91e6b2") } > db.demo627.insertOne({id:102,"Name":"Bob","Marks":74}); { "acknowledged" : true, "insertedId" : ObjectId("5e9acb3c6c954c74be91e6b3") } > db.demo627.insertOne({id:101,"Name":"Chris","Marks":87}); { "acknowledged" : true, "insertedId" : ObjectId("5e9acb426c954c74be91e6b4") } > db.demo627.insertOne({id:102,"Name":"Mike","Marks":70}); { "acknowledged" : true, "insertedId" : ObjectId("5e9acb4b6c954c74be91e6b5") }
Display all documents from a collection with the help of find() method −
> db.demo627.find();
This will produce the following output −
{ "_id" : ObjectId("5e9acb306c954c74be91e6b2"), "id" : 101, "Name" : "Chris", "Marks" : 54 } { "_id" : ObjectId("5e9acb3c6c954c74be91e6b3"), "id" : 102, "Name" : "Bob", "Marks" : 74 } { "_id" : ObjectId("5e9acb426c954c74be91e6b4"), "id" : 101, "Name" : "Chris", "Marks" : 87 } { "_id" : ObjectId("5e9acb4b6c954c74be91e6b5"), "id" : 102, "Name" : "Mike", "Marks" : 70 }
Following is the query to sum with MongoDB group by multiple columns to calculate total marks with duplicate ids −
> db.demo627.aggregate([ ... { "$group": { ... "_id": { ... "id" : "$id", .. . "Name":"$Name" ... }, ... "Marks": { "$sum": "$Marks" } ... }}, ... { "$group": { ... "_id": { ... "id" : "$_id.id", ... "Name": "$_id.Name" ... }, ... ... "TotalMarks": { "$sum": "$Marks" } ... }} ... ], { "allowDiskUse": true } ... );
This will produce the following output −
{ "_id" : { "id" : 101, "Name" : "Chris" }, "TotalMarks" : 141 } { "_id" : { "id" : 102, "Name" : "Bob" }, "TotalMarks" : 74 } { "_id" : { "id" : 102, "Name" : "Mike" }, "TotalMarks" : 70 }