- 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
MongoDB query to 'sort' and display a specific number of values
To sort in MongoDB, use sort(). For displaying only a specific number of values, use LIMIT. Let us create a collection with documents −
> db.demo254.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e47a0ab1627c0c63e7dba7f") } > db.demo254.insertOne({"Name":"Adam"}); { "acknowledged" : true, "insertedId" : ObjectId("5e47a0b01627c0c63e7dba80") } > db.demo254.insertOne({"Name":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e47a0b71627c0c63e7dba81") }
Display all documents from a collection with the help of find() method −
> db.demo254.find();
This will produce the following output −
{ "_id" : ObjectId("5e47a0ab1627c0c63e7dba7f"), "Name" : "Chris" } { "_id" : ObjectId("5e47a0b01627c0c63e7dba80"), "Name" : "Adam" } { "_id" : ObjectId("5e47a0b71627c0c63e7dba81"), "Name" : "Bob" }
Following is the query to sort −
> db.demo254.find().sort({"Name":1});
This will produce the following output −
{ "_id" : ObjectId("5e47a0b01627c0c63e7dba80"), "Name" : "Adam" } { "_id" : ObjectId("5e47a0b71627c0c63e7dba81"), "Name" : "Bob" } { "_id" : ObjectId("5e47a0ab1627c0c63e7dba7f"), "Name" : "Chris" }
Following is the query to sort and display only a specific number of records with limit().
> db.demo254.find().sort({"Name":1}).limit(2);
This will produce the following output −
{ "_id" : ObjectId("5e47a0b01627c0c63e7dba80"), "Name" : "Adam" } { "_id" : ObjectId("5e47a0b71627c0c63e7dba81"), "Name" : "Bob" }
Advertisements