MongoDB query to get last inserted document?

To get the last inserted document in MongoDB, use sort() with _id in descending order along with limit(1). Since ObjectId contains a timestamp, sorting by _id in descending order retrieves the most recently inserted document.

Syntax

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

Sample Data

Let us first create a collection with documents ?

db.getLastInsertedDocument.insertMany([
    {"Name": "John"},
    {"Name": "Chris"},
    {"Name": "Robert"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cefb17eef71edecf6a1f6a8"),
        ObjectId("5cefb181ef71edecf6a1f6a9"),
        ObjectId("5cefb185ef71edecf6a1f6aa")
    ]
}

Display all documents from the collection ?

db.getLastInsertedDocument.find();
{ "_id": ObjectId("5cefb17eef71edecf6a1f6a8"), "Name": "John" }
{ "_id": ObjectId("5cefb181ef71edecf6a1f6a9"), "Name": "Chris" }
{ "_id": ObjectId("5cefb185ef71edecf6a1f6aa"), "Name": "Robert" }

Example

Following is the query to get the last inserted document ?

db.getLastInsertedDocument.find().sort({_id: -1}).limit(1);
{ "_id": ObjectId("5cefb185ef71edecf6a1f6aa"), "Name": "Robert" }

How It Works

  • sort({_id: -1}) sorts documents by _id in descending order (newest first)
  • limit(1) returns only the first document from the sorted result
  • ObjectId contains a timestamp, making _id sorting reliable for insertion order

Conclusion

Use find().sort({_id: -1}).limit(1) to efficiently retrieve the most recently inserted document. This method leverages ObjectId's built-in timestamp for accurate ordering.

Updated on: 2026-03-15T01:26:55+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements