In MongoDB, what is the most efficient way to get the first and last document?

To get the first and last document in MongoDB, use aggregate() with $first and $last operators within a $group stage. This efficiently retrieves both documents in a single operation.

Syntax

db.collection.aggregate([
    {
        $group: {
            _id: null,
            first: { $first: "$$ROOT" },
            last: { $last: "$$ROOT" }
        }
    }
]);

Sample Data

db.demo73.insertMany([
    {"Name": "Chris"},
    {"Name": "Bob"},
    {"Name": "David"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e29c41b71bf0181ecc4226c"),
        ObjectId("5e29c41e71bf0181ecc4226d"),
        ObjectId("5e29c42271bf0181ecc4226e")
    ]
}

Display All Documents

db.demo73.find();
{ "_id": ObjectId("5e29c41b71bf0181ecc4226c"), "Name": "Chris" }
{ "_id": ObjectId("5e29c41e71bf0181ecc4226d"), "Name": "Bob" }
{ "_id": ObjectId("5e29c42271bf0181ecc4226e"), "Name": "David" }

Get First and Last Document

db.demo73.aggregate([
    {
        $group: {
            _id: null,
            first: { $first: "$$ROOT" },
            last: { $last: "$$ROOT" }
        }
    }
]);
{
    "_id": null,
    "first": { "_id": ObjectId("5e29c41b71bf0181ecc4226c"), "Name": "Chris" },
    "last": { "_id": ObjectId("5e29c42271bf0181ecc4226e"), "Name": "David" }
}

How It Works

  • $group with _id: null processes all documents as one group
  • $first returns the first document in processing order
  • $last returns the last document in processing order
  • $$ROOT refers to the entire document

Conclusion

Using aggregate() with $first and $last operators is the most efficient way to retrieve both the first and last documents in a single query. The $$ROOT variable captures complete document details.

Updated on: 2026-03-15T01:50:27+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements