Sort and get only the first two fields in a "$group" operation in MongoDB

To sort documents and get only the first document per group in MongoDB's $group operation, use $sort before grouping, then $first with $$ROOT to capture the entire document, and finally $project to shape the output fields.

Syntax

db.collection.aggregate([
    { $sort: { "field": 1 } },
    { $group: {
        "_id": "$groupField",
        "result": { $first: "$$ROOT" }
    }},
    { $project: {
        "field1": "$result.field1",
        "field2": "$result.field2"
    }}
]);

Sample Data

db.demo576.insertMany([
    { id: 101, Name: "Chris", Marks: 45 },
    { id: 101, Name: "John", Marks: 55 },
    { id: 101, Name: "John", Marks: 65 },
    { id: 102, Name: "David", Marks: 37 },
    { id: 102, Name: "David", Marks: 75 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e916c3b581e9acd78b427fa"),
        ObjectId("5e916c43581e9acd78b427fb"),
        ObjectId("5e916c47581e9acd78b427fc"),
        ObjectId("5e916c55581e9acd78b427fd"),
        ObjectId("5e916c5e581e9acd78b427fe")
    ]
}

Display All Documents

db.demo576.find();
{ "_id": ObjectId("5e916c3b581e9acd78b427fa"), "id": 101, "Name": "Chris", "Marks": 45 }
{ "_id": ObjectId("5e916c43581e9acd78b427fb"), "id": 101, "Name": "John", "Marks": 55 }
{ "_id": ObjectId("5e916c47581e9acd78b427fc"), "id": 101, "Name": "John", "Marks": 65 }
{ "_id": ObjectId("5e916c55581e9acd78b427fd"), "id": 102, "Name": "David", "Marks": 37 }
{ "_id": ObjectId("5e916c5e581e9acd78b427fe"), "id": 102, "Name": "David", "Marks": 75 }

Get First Document by Minimum Marks per Group

Sort by Marks in ascending order and get the first document for each id group ?

db.demo576.aggregate([
    {
        "$sort": { "Marks": 1 }
    },
    {
        "$group": {
            "_id": "$id",
            "out": { "$first": "$$ROOT" }
        }
    },
    {
        "$project": {
            "_id": "$out._id",
            "id": "$out.id",
            "Name": "$out.Name",
            "MinMarks": "$out.Marks"
        }
    }
]);
{ "_id": ObjectId("5e916c3b581e9acd78b427fa"), "id": 101, "Name": "Chris", "MinMarks": 45 }
{ "_id": ObjectId("5e916c55581e9acd78b427fd"), "id": 102, "Name": "David", "MinMarks": 37 }

How It Works

  1. $sort orders documents by Marks in ascending order (lowest first)
  2. $group groups by id and captures the first document using $first: "$$ROOT"
  3. $project reshapes the output to show desired fields, renaming Marks to MinMarks

Conclusion

Use $sort before $group with $first and $$ROOT to get the first document per group. The $project stage allows you to reshape and rename output fields as needed.

Updated on: 2026-03-15T03:43:40+05:30

377 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements