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.

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

5 ★ | 1 Vote