MongoDB aggregation to get two documents with the least marks

To get the two documents with the least marks in MongoDB, use the aggregation pipeline with $sort to order by marks in ascending order and $limit: 2 to restrict the result to only two documents.

Syntax

db.collection.aggregate([
    { $sort: { "field": 1 } },
    { $limit: 2 }
]);

Sample Data

db.demo709.insertMany([
    { "Name": "John", "Marks": 75 },
    { "Name": "Chris", "Marks": 45 },
    { "Name": "David", "Marks": 54 },
    { "Name": "Bob", "Marks": 69 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5ea839005d33e20ed1097b76"),
        ObjectId("5ea839075d33e20ed1097b77"),
        ObjectId("5ea839125d33e20ed1097b78"),
        ObjectId("5ea839295d33e20ed1097b79")
    ]
}

Display all documents from the collection ?

db.demo709.find();
{ "_id": ObjectId("5ea839005d33e20ed1097b76"), "Name": "John", "Marks": 75 }
{ "_id": ObjectId("5ea839075d33e20ed1097b77"), "Name": "Chris", "Marks": 45 }
{ "_id": ObjectId("5ea839125d33e20ed1097b78"), "Name": "David", "Marks": 54 }
{ "_id": ObjectId("5ea839295d33e20ed1097b79"), "Name": "Bob", "Marks": 69 }

Method 1: Direct Sort and Limit

Get the two documents with the lowest marks ?

db.demo709.aggregate([
    { $sort: { "Marks": 1 } },
    { $limit: 2 }
]);
{ "_id": ObjectId("5ea839075d33e20ed1097b77"), "Name": "Chris", "Marks": 45 }
{ "_id": ObjectId("5ea839125d33e20ed1097b78"), "Name": "David", "Marks": 54 }

Method 2: Group by Marks and Limit

Group students by their marks and get the two lowest mark groups ?

db.demo709.aggregate([
    {
        $group: {
            _id: "$Marks",
            ListOfName: { $push: "$Name" }
        }
    },
    { $sort: { "_id": 1 } },
    { $limit: 2 }
]);
{ "_id": 45, "ListOfName": ["Chris"] }
{ "_id": 54, "ListOfName": ["David"] }

Conclusion

Use $sort with ascending order (1) followed by $limit to retrieve documents with the lowest values. Method 1 returns individual documents, while Method 2 groups by marks which is useful when multiple students have the same score.

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

204 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements