- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort MongoDB documents in descending order
To sort documents, use sort() along with find(). Let us create a collection with documents −
> db.demo630.insertOne({"Value":10}); { "acknowledged" : true, "insertedId" : ObjectId("5e9b080e6c954c74be91e6ba") } > db.demo630.insertOne({"Value":200}); { "acknowledged" : true, "insertedId" : ObjectId("5e9b08116c954c74be91e6bb") } > db.demo630.insertOne({"Value":40}); { "acknowledged" : true, "insertedId" : ObjectId("5e9b08146c954c74be91e6bc") } > db.demo630.insertOne({"Value":60}); { "acknowledged" : true, "insertedId" : ObjectId("5e9b08176c954c74be91e6bd") }
Display all documents from a collection with the help of find() method −
> db.demo630.find();
This will produce the following output −
{ "_id" : ObjectId("5e9b080e6c954c74be91e6ba"), "Value" : 10 } { "_id" : ObjectId("5e9b08116c954c74be91e6bb"), "Value" : 200 } { "_id" : ObjectId("5e9b08146c954c74be91e6bc"), "Value" : 40 } { "_id" : ObjectId("5e9b08176c954c74be91e6bd"), "Value" : 60 }
Following is the query to sort −
> db.demo630.find().sort({Value:-1});
This will produce the following output −
{ "_id" : ObjectId("5e9b08116c954c74be91e6bb"), "Value" : 200 } { "_id" : ObjectId("5e9b08176c954c74be91e6bd"), "Value" : 60 } { "_id" : ObjectId("5e9b08146c954c74be91e6bc"), "Value" : 40 } { "_id" : ObjectId("5e9b080e6c954c74be91e6ba"), "Value" : 10 }
Advertisements