- 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
Sorting field value (FirstName) for MongoDB?
To sort values, use sort() in MongoDB. Let us first create a collection with documents −
> db.demo365.insertOne({"FirstName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e57d5b6d0ada61456dc936f") } > db.demo365.insertOne({"FirstName":"Adam"}); { "acknowledged" : true, "insertedId" : ObjectId("5e57d5bad0ada61456dc9370") } > db.demo365.insertOne({"FirstName":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5e57d5bed0ada61456dc9371") } > db.demo365.insertOne({"FirstName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e57d5c0d0ada61456dc9372") }
Display all documents from a collection with the help of find() method −
> db.demo365.find();
This will produce the following output −
{ "_id" : ObjectId("5e57d5b6d0ada61456dc936f"), "FirstName" : "Chris" } { "_id" : ObjectId("5e57d5bad0ada61456dc9370"), "FirstName" : "Adam" } { "_id" : ObjectId("5e57d5bed0ada61456dc9371"), "FirstName" : "John" } { "_id" : ObjectId("5e57d5c0d0ada61456dc9372"), "FirstName" : "Bob" }
Following is the query for sorting −
> db.demo365.find().sort({"FirstName":1});
This will produce the following output −
{ "_id" : ObjectId("5e57d5bad0ada61456dc9370"), "FirstName" : "Adam" } { "_id" : ObjectId("5e57d5c0d0ada61456dc9372"), "FirstName" : "Bob" } { "_id" : ObjectId("5e57d5b6d0ada61456dc936f"), "FirstName" : "Chris" } { "_id" : ObjectId("5e57d5bed0ada61456dc9371"), "FirstName" : "John" }
Advertisements