Sort records in MongoDB

To sort documents in MongoDB, you need to use the sort () method. The sort () method takes a Document containing a list of fields with their sort order. To determine the sort order, 1 and -1 are used. 1 is used for ascending order, while -1 is used for descending order.

Table of Contents

Sort () method in MongoDB

To sort documents in MongoDB, you need to use the sort () method . The sort () method takes a Document containing a list of fields with their sort order. To determine the sort order, 1 and -1 are used. 1 is used for ascending order, while -1 is used for descending order.

Syntax

The basic syntax of sort () method is as follows:

 > db . COLLECTION_NAME . find (). sort ({ KEY : 1 }) 

For example

You follow Collection with the name mycol with the following data:

 { "_id" : ObjectId ( 5983548781331adf45ec5 ), "title" : "MongoDB Overview" } { "_id" : ObjectId ( 5983548781331adf45ec6 ), "title" : "NoSQL Overview" } { "_id" : ObjectId ( 5983548781331adf45ec7 ), "title" : "Tutorials Point Overview" } 

The following example displays the Document sorted by title in descending order.

 > db . mycol . find ({},{ "title" : 1 , _id : 0 }). sort ({ "title" :- 1 }) { "title" : "Tutorials Point Overview" } { "title" : "NoSQL Overview" } { "title" : "MongoDB Overview" } > 

Remember if you don't specify the sort order, the sort () method will display the Document in ascending order.

According to Tutorialspoint

Previous post: Limit the record in MongoDB

Next lesson: Index (Index) in MongoDB

You've just finished reading the article "Sort records in MongoDB" edited by the TipsMake team. You can save sort-records-in-mongodb.pdf to your computer here to read later or print it out. We hope this article has provided you with many useful tech tips and tricks. You can search for similar articles on tips and guides. Thank you for reading and for following us regularly.

« PREV Index (Mong) in MongoDB
NEXT » Limit records in MongoDB