

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How we can perform sort on ObjectId column in MongoDB?
To perform sort on ObjectId column, use sort(). Let us create a collection with document.
> db.demo403.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e6f89b0fac4d418a017858e") } > db.demo403.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e6f89b2fac4d418a017858f") } > db.demo403.insertOne({"Name":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e6f89b5fac4d418a0178590") } > db.demo403.insertOne({"Name":"Adam"}); { "acknowledged" : true, "insertedId" : ObjectId("5e6f89b8fac4d418a0178591") }
Display all documents from a collection with the help of find() method −
> db.demo403.find();
This will produce the following output −
{ "_id" : ObjectId("5e6f89b0fac4d418a017858e"), "Name" : "Chris" } { "_id" : ObjectId("5e6f89b2fac4d418a017858f"), "Name" : "David" } { "_id" : ObjectId("5e6f89b5fac4d418a0178590"), "Name" : "Bob" } { "_id" : ObjectId("5e6f89b8fac4d418a0178591"), "Name" : "Adam" }
Following is the query to perform sort on ObjectId column in MongoDB −
> db.demo403.find().sort({_id:-1});
This will produce the following output −
{ "_id" : ObjectId("5e6f89b8fac4d418a0178591"), "Name" : "Adam" } { "_id" : ObjectId("5e6f89b5fac4d418a0178590"), "Name" : "Bob" } { "_id" : ObjectId("5e6f89b2fac4d418a017858f"), "Name" : "David" } { "_id" : ObjectId("5e6f89b0fac4d418a017858e"), "Name" : "Chris" }
- Related Questions & Answers
- How can we sort a JTable on a particular column in Java?
- Perform aggregation sort in MongoDB?
- How to generate ObjectID in MongoDB?
- How to perform ascending order sort in MongoDB?
- How to perform descending order sort in MongoDB?
- Perform Bubble Sort on strings in Java
- Display MongoDB records by ObjectId?
- Convert string to objectid in MongoDB?
- How to convert ObjectId to string in MongoDB
- Find a document with ObjectID in MongoDB?
- How can we sort a JSONObject in Java?
- How can we sort a JSONArray in Java?
- Create ObjectId in MongoDB using a seed string?
- Cast to ObjectId failed for value in MongoDB?
- How can we sort MySQL output in descending order?
Advertisements