Find maximum score for duplicate Name values in MongoDB?


To find maximum score, use GROUP() to group documents in a collection. Let us create a collection with documents −

> db.demo114.insertOne({"Score":60,"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2efc57d8f64a552dae6354")
}
> db.demo114.insertOne({"Score":87,"Nam+e":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2efc5ad8f64a552dae6355")
}
> db.demo114.insertOne({"Score":45,"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2efc5dd8f64a552dae6356")
}
> db.demo114.insertOne({"Score":67,"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2efc68d8f64a552dae6357")
}
> db.demo114.insertOne({"Score":38,"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2efc74d8f64a552dae6358")
}

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

> db.demo114.find();

This will produce the following output −

{ "_id" : ObjectId("5e2efc57d8f64a552dae6354"), "Score" : 60, "Name" : "Chris" }
{ "_id" : ObjectId("5e2efc5ad8f64a552dae6355"), "Score" : 87, "Name" : "Chris" }
{ "_id" : ObjectId("5e2efc5dd8f64a552dae6356"), "Score" : 45, "Name" : "David" }
{ "_id" : ObjectId("5e2efc68d8f64a552dae6357"), "Score" : 67, "Name" : "Chris" }
{ "_id" : ObjectId("5e2efc74d8f64a552dae6358"), "Score" : 38, "Name" : "David" }

Following is the query to find maximum. This calculates the maximum score of let’s say duplicate name values, such as “Chris” and “David” −

> db.demo114.group(
...    {key: {Name:true},
...    reduce: function(c,p) {
...       if (p.maximumScore < c.Score) {
...          p.maximumScore = c.Score;
...       }
...    },
...    initial: { maximumScore: 0 }}
... );

This will produce the following output −

[
   {
      "Name" : "Chris",
      "maximumScore" : 87
   },
   {
      "Name" : "David",
      "maximumScore" : 45
   }
]

Updated on: 30-Mar-2020

92 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements