How to get max values for distinct elements in MongoDB

To get max values for distinct elements in MongoDB, use the $group operator with $max to find the highest value for each distinct element. This aggregation pipeline groups documents by a field and returns the maximum value within each group.

Syntax

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

Sample Data

db.demo750.insertMany([
    { id: 101, value: 50 },
    { id: 102, value: 40 },
    { id: 101, value: 110 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5eae74b2a930c785c834e566"),
        ObjectId("5eae74c8a930c785c834e567"),
        ObjectId("5eae74dba930c785c834e568")
    ]
}

Display all documents from the collection ?

db.demo750.find();
{ "_id": ObjectId("5eae74b2a930c785c834e566"), "id": 101, "value": 50 }
{ "_id": ObjectId("5eae74c8a930c785c834e567"), "id": 102, "value": 40 }
{ "_id": ObjectId("5eae74dba930c785c834e568"), "id": 101, "value": 110 }

Method 1: Using $max (Recommended)

Get the maximum value for each distinct id ?

db.demo750.aggregate([
    {
        $group: {
            _id: "$id",
            maxValue: { $max: "$value" }
        }
    }
]);
{ "_id": 102, "maxValue": 40 }
{ "_id": 101, "maxValue": 110 }

Method 2: Using $sort with $first

Alternative approach using sort and first ?

db.demo750.aggregate([
    {
        $sort: { value: -1 }
    },
    {
        $group: {
            _id: "$id",
            value: { $first: "$value" }
        }
    },
    {
        $project: {
            id: "$_id",
            value: 1
        }
    }
]);
{ "_id": 102, "value": 40, "id": 102 }
{ "_id": 101, "value": 110, "id": 101 }

Key Points

  • $max is more efficient for finding maximum values than sorting.
  • $group by the field you want distinct values for.
  • Use $project to reshape the output if needed.

Conclusion

Use $group with $max to efficiently find maximum values for distinct elements. This approach directly calculates the maximum without requiring sorting, making it the preferred method for this operation.

Updated on: 2026-03-15T03:56:04+05:30

762 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements