How to get element with max id in MongoDB?

To get the element with the maximum _id in MongoDB, use the sort() method with descending order and limit(1) to retrieve only the document with the highest _id value.

Syntax

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

Sample Data

db.getElementWithMaxIdDemo.insertMany([
    {"Name": "John", "Age": 21},
    {"Name": "Larry", "Age": 24},
    {"Name": "David", "Age": 23},
    {"Name": "Chris", "Age": 20},
    {"Name": "Robert", "Age": 25}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c8bbce480f10143d8431e1c"),
        ObjectId("5c8bbcec80f10143d8431e1d"),
        ObjectId("5c8bbcf580f10143d8431e1e"),
        ObjectId("5c8bbcfe80f10143d8431e1f"),
        ObjectId("5c8bbd0880f10143d8431e20")
    ]
}

Display All Documents

db.getElementWithMaxIdDemo.find();
{
    "_id": ObjectId("5c8bbce480f10143d8431e1c"),
    "Name": "John",
    "Age": 21
}
{
    "_id": ObjectId("5c8bbcec80f10143d8431e1d"),
    "Name": "Larry",
    "Age": 24
}
{
    "_id": ObjectId("5c8bbcf580f10143d8431e1e"),
    "Name": "David",
    "Age": 23
}
{
    "_id": ObjectId("5c8bbcfe80f10143d8431e1f"),
    "Name": "Chris",
    "Age": 20
}
{
    "_id": ObjectId("5c8bbd0880f10143d8431e20"),
    "Name": "Robert",
    "Age": 25
}

Get Element with Maximum ID

db.getElementWithMaxIdDemo.find().sort({_id: -1}).limit(1);
{
    "_id": ObjectId("5c8bbd0880f10143d8431e20"),
    "Name": "Robert",
    "Age": 25
}

How It Works

  • sort({_id: -1}) sorts documents by _id in descending order (highest first)
  • limit(1) returns only the first document from the sorted result
  • Since ObjectId values increase over time, the highest _id represents the most recently inserted document

Conclusion

Use sort({_id: -1}).limit(1) to efficiently retrieve the document with the maximum _id value. This approach leverages MongoDB's natural ObjectId ordering to find the most recent document.

Updated on: 2026-03-15T00:12:12+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements