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 we can perform sort on ObjectId column in MongoDB?
To perform sort on ObjectId column in MongoDB, use the sort() method with the _id field. ObjectIds are sorted by their creation timestamp, making them useful for chronological ordering.
Syntax
db.collection.find().sort({_id: 1}); // Ascending (oldest first)
db.collection.find().sort({_id: -1}); // Descending (newest first)
Sample Data
db.demo403.insertMany([
{"Name": "Chris"},
{"Name": "David"},
{"Name": "Bob"},
{"Name": "Adam"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e6f89b0fac4d418a017858e"),
ObjectId("5e6f89b2fac4d418a017858f"),
ObjectId("5e6f89b5fac4d418a0178590"),
ObjectId("5e6f89b8fac4d418a0178591")
]
}
Display all documents from the collection ?
db.demo403.find();
{ "_id": ObjectId("5e6f89b0fac4d418a017858e"), "Name": "Chris" }
{ "_id": ObjectId("5e6f89b2fac4d418a017858f"), "Name": "David" }
{ "_id": ObjectId("5e6f89b5fac4d418a0178590"), "Name": "Bob" }
{ "_id": ObjectId("5e6f89b8fac4d418a0178591"), "Name": "Adam" }
Example: Sort by ObjectId in Descending Order
Sort documents by ObjectId in descending order (newest first) ?
db.demo403.find().sort({_id: -1});
{ "_id": ObjectId("5e6f89b8fac4d418a0178591"), "Name": "Adam" }
{ "_id": ObjectId("5e6f89b5fac4d418a0178590"), "Name": "Bob" }
{ "_id": ObjectId("5e6f89b2fac4d418a017858f"), "Name": "David" }
{ "_id": ObjectId("5e6f89b0fac4d418a017858e"), "Name": "Chris" }
Key Points
- Use
1for ascending order (oldest ObjectIds first) - Use
-1for descending order (newest ObjectIds first) - ObjectIds contain timestamps, so sorting by
_ideffectively sorts by creation time
Conclusion
The sort({_id: -1}) method efficiently orders documents by their ObjectId values. Since ObjectIds embed creation timestamps, this provides chronological sorting without requiring separate date fields.
Advertisements
