Identify last document from MongoDB find() result set?

To identify the last document from a MongoDB find() result set, use the sort() method with descending order on the _id field, combined with limit(1) to get only the most recent document.

Syntax

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

Sample Data

Let's create a collection with sample documents to demonstrate identifying the last document ?

db.identifyLastDocumentDemo.insertMany([
    {"UserName": "Larry", "UserAge": 24, "UserCountryName": "US"},
    {"UserName": "Chris", "UserAge": 21, "UserCountryName": "UK"}, 
    {"UserName": "David", "UserAge": 25, "UserCountryName": "AUS"},
    {"UserName": "Sam", "UserAge": 26, "UserCountryName": "US"},
    {"UserName": "Mike", "UserAge": 27, "UserCountryName": "AUS"},
    {"UserName": "Carol", "UserAge": 28, "UserCountryName": "UK"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c94a2ff4cf1f7a64fa4df57"),
        ObjectId("5c94a3094cf1f7a64fa4df58"),
        ObjectId("5c94a3174cf1f7a64fa4df59"),
        ObjectId("5c94a3224cf1f7a64fa4df5a"),
        ObjectId("5c94a32e4cf1f7a64fa4df5b"),
        ObjectId("5c94a33c4cf1f7a64fa4df5c")
    ]
}

Display All Documents

db.identifyLastDocumentDemo.find();
{
    "_id": ObjectId("5c94a2ff4cf1f7a64fa4df57"),
    "UserName": "Larry",
    "UserAge": 24,
    "UserCountryName": "US"
}
{
    "_id": ObjectId("5c94a3094cf1f7a64fa4df58"),
    "UserName": "Chris", 
    "UserAge": 21,
    "UserCountryName": "UK"
}
{
    "_id": ObjectId("5c94a3174cf1f7a64fa4df59"),
    "UserName": "David",
    "UserAge": 25, 
    "UserCountryName": "AUS"
}
{
    "_id": ObjectId("5c94a3224cf1f7a64fa4df5a"),
    "UserName": "Sam",
    "UserAge": 26,
    "UserCountryName": "US"
}
{
    "_id": ObjectId("5c94a32e4cf1f7a64fa4df5b"),
    "UserName": "Mike",
    "UserAge": 27,
    "UserCountryName": "AUS"
}
{
    "_id": ObjectId("5c94a33c4cf1f7a64fa4df5c"),
    "UserName": "Carol",
    "UserAge": 28,
    "UserCountryName": "UK"
}

Get Last Document

Query to identify the last document from the find() result set ?

db.identifyLastDocumentDemo.find().sort({ _id: -1 }).limit(1);
{
    "_id": ObjectId("5c94a33c4cf1f7a64fa4df5c"),
    "UserName": "Carol",
    "UserAge": 28,
    "UserCountryName": "UK"
}

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
  • Since _id contains a timestamp, the highest _id represents the most recently inserted document

Conclusion

Use sort({ _id: -1 }).limit(1) to efficiently retrieve the last inserted document. The _id field's timestamp component makes it ideal for identifying the most recent document in MongoDB collections.

Updated on: 2026-03-15T00:22:04+05:30

265 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements