Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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_idin descending order (highest first) -
limit(1)returns only the first document from the sorted result - Since ObjectId values increase over time, the highest
_idrepresents 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.
Advertisements
