How to select maximum item in each group with MongoDB?

To select the maximum item in each group with MongoDB, use the $group aggregation stage with the $max operator. This groups documents by a field and finds the maximum value within each group.

Syntax

db.collection.aggregate([
    {
        $group: {
            _id: { fieldName: "$fieldName" },
            maxField: { $max: "$valueField" }
        }
    }
]);

Sample Data

db.students.insertMany([
    { Name: "Chris", CountryName: "US", Marks: 50 },
    { Name: "David", CountryName: "US", Marks: 60 },
    { Name: "Mike", CountryName: "US", Marks: 55 },
    { Name: "Chris", CountryName: "UK", Marks: 75 },
    { Name: "David", CountryName: "UK", Marks: 54 },
    { Name: "Mike", CountryName: "UK", Marks: 72 }
]);
{
    "acknowledged": true,
    "insertedIds": [ObjectId("..."), ObjectId("..."), ...]
}

Display Sample Data

db.students.find();
{ "_id": ObjectId("..."), "Name": "Chris", "CountryName": "US", "Marks": 50 }
{ "_id": ObjectId("..."), "Name": "David", "CountryName": "US", "Marks": 60 }
{ "_id": ObjectId("..."), "Name": "Mike", "CountryName": "US", "Marks": 55 }
{ "_id": ObjectId("..."), "Name": "Chris", "CountryName": "UK", "Marks": 75 }
{ "_id": ObjectId("..."), "Name": "David", "CountryName": "UK", "Marks": 54 }
{ "_id": ObjectId("..."), "Name": "Mike", "CountryName": "UK", "Marks": 72 }

Example: Find Maximum Marks by Country

db.students.aggregate([
    {
        $group: {
            _id: { CountryName: "$CountryName" },
            MaxMarks: { $max: "$Marks" }
        }
    }
]);
{ "_id": { "CountryName": "UK" }, "MaxMarks": 75 }
{ "_id": { "CountryName": "US" }, "MaxMarks": 60 }

Key Points

  • The $group stage groups documents by the specified _id field
  • $max operator finds the maximum value within each group
  • Results show the highest marks for each country: UK (75) and US (60)

Conclusion

Use $group with $max to efficiently find maximum values within grouped data. This aggregation approach scales well for large datasets and complex grouping requirements.

Updated on: 2026-03-15T03:25:57+05:30

441 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements