MongoDB query to find last object in collection?

To find the last object in a MongoDB collection, use the sort() method to sort documents in descending order by _id, then apply limit(1) to retrieve only the most recent document.

Syntax

db.collection.find().sort({_id: -1}).limit(1);

Sample Data

Let us create a collection with sample documents −

db.demo141.insertMany([
    {"Name": "Chris"},
    {"Name": "David"},
    {"Name": "Bob"},
    {"Name": "Mike"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e31c347fdf09dd6d08539ae"),
        ObjectId("5e31c34bfdf09dd6d08539af"),
        ObjectId("5e31c34ffdf09dd6d08539b0"),
        ObjectId("5e31c352fdf09dd6d08539b1")
    ]
}

Display all documents from the collection −

db.demo141.find();
{ "_id": ObjectId("5e31c347fdf09dd6d08539ae"), "Name": "Chris" }
{ "_id": ObjectId("5e31c34bfdf09dd6d08539af"), "Name": "David" }
{ "_id": ObjectId("5e31c34ffdf09dd6d08539b0"), "Name": "Bob" }
{ "_id": ObjectId("5e31c352fdf09dd6d08539b1"), "Name": "Mike" }

Example

Query to find the last object in the collection −

db.demo141.find().sort({_id: -1}).limit(1);
{ "_id": ObjectId("5e31c352fdf09dd6d08539b1"), "Name": "Mike" }

How It Works

  • sort({_id: -1}) sorts documents in descending order by ObjectId
  • limit(1) returns only the first document from the sorted result
  • Since ObjectId contains a timestamp, the last inserted document has the highest _id value

Conclusion

Use sort({_id: -1}).limit(1) to efficiently retrieve the last inserted document. This approach leverages the timestamp embedded in MongoDB's ObjectId for chronological ordering.

Updated on: 2026-03-15T02:14:11+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements