

- 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 to specify the order in which the query returns matching documents 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" }
- Related Questions & Answers
- MongoDB query for documents matching array, irrespective of elements order
- MongoDB query to update all documents matching specific IDs
- MongoDB query to find matching documents given an array with values?
- Sort the MongoDB documents in ascending order with aggregation?
- MongoDB query to skip documents
- MongoDB query to select 10 most recent documents without changing order?
- Sort MongoDB documents in descending order
- MongoDB - Query embedded documents?
- How to query documents by a condition on the subdocument in MongoDB?
- Get the size of all the documents in a MongoDB query?
- MongoDB query to add multiple documents
- MongoDB query to group duplicate documents
- MongoDB query to count records on the basis of matching criteria
- MongoDB Group query to get the count of repeated marks in documents?
- How to fire find query on sub-documents in MongoDB?
Advertisements