
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Specify Order of Query Results in MongoDB
To specify the order in which the query returns matching documents, use cursor.sort() in MongoDB. The cursor is db.collectionName.find().
Let us create a collection with documents −
> db.demo259.insertOne({"Subject":"MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5e47ae1f1627c0c63e7dba98") } > db.demo259.insertOne({"Subject":"Java"}); { "acknowledged" : true, "insertedId" : ObjectId("5e47ae231627c0c63e7dba99") } > db.demo259.insertOne({"Subject":"MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5e47ae281627c0c63e7dba9a") }
Display all documents from a collection with the help of find() method −
> db.demo259.find();
This will produce the following output −
{ "_id" : ObjectId("5e47ae1f1627c0c63e7dba98"), "Subject" : "MySQL" } { "_id" : ObjectId("5e47ae231627c0c63e7dba99"), "Subject" : "Java" } { "_id" : ObjectId("5e47ae281627c0c63e7dba9a"), "Subject" : "MongoDB" }
Following is the query to sort with a specific order −
> db.demo259.find().sort({"Subject":1});
This will produce the following output −
{ "_id" : ObjectId("5e47ae231627c0c63e7dba99"), "Subject" : "Java" } { "_id" : ObjectId("5e47ae281627c0c63e7dba9a"), "Subject" : "MongoDB" } { "_id" : ObjectId("5e47ae1f1627c0c63e7dba98"), "Subject" : "MySQL" }
Advertisements