How to select maximum item in each group with MongoDB?


You can use $group. Let us create a collection with documents −

> db.demo659.insertOne({Name:"Chris",CountryName:"US","Marks":50});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea1a50724113ea5458c7cf9")
}
> db.demo659.insertOne({Name:"David",CountryName:"US","Marks":60});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea1a50724113ea5458c7cfa")
}
> db.demo659.insertOne({Name:"Mike",CountryName:"US","Marks":55});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea1a50724113ea5458c7cfb")
}
> db.demo659.insertOne({Name:"Chris",CountryName:"UK","Marks":75});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea1a50724113ea5458c7cfc")
}
> db.demo659.insertOne({Name:"David",CountryName:"UK","Marks":54});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea1a50724113ea5458c7cfd")
}
> db.demo659.insertOne({Name:"Mike",CountryName:"UK","Marks":72});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea1a50824113ea5458c7cfe")
}

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

> db.demo659.find();

This will produce the following output. It finds maximum marks from each i.e. CountryName US and UK −

{ "_id" : ObjectId("5ea1a50724113ea5458c7cf9"), "Name" : "Chris", "CountryName" : "US", "Marks" : 50 }
{ "_id" : ObjectId("5ea1a50724113ea5458c7cfa"), "Name" : "David", "CountryName" : "US", "Marks" : 60 }
{ "_id" : ObjectId("5ea1a50724113ea5458c7cfb"), "Name" : "Mike", "CountryName" : "US", "Marks" : 55 }
{ "_id" : ObjectId("5ea1a50724113ea5458c7cfc"), "Name" : "Chris", "CountryName" : "UK", "Marks" : 75 }
{ "_id" : ObjectId("5ea1a50724113ea5458c7cfd"), "Name" : "David", "CountryName" : "UK", "Marks" : 54 }
{ "_id" : ObjectId("5ea1a50824113ea5458c7cfe"), "Name" : "Mike", "CountryName" : "UK", "Marks" : 72 }

Following is the query to select max item in each group −

> db.demo659.aggregate( { $group: {
...    _id: {CountryName: "$CountryName" },
...    'MaxMarks': { $max : "$Marks" }
... }})

This will produce the following output −

{ "_id" : { "CountryName" : "UK" }, "MaxMarks" : 75 }
{ "_id" : { "CountryName" : "US" }, "MaxMarks" : 60 }

Updated on: 13-May-2020

308 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements