MongoDB - Sorting Records

MongoDB - Sorting Records

sort() method

To sort documents in MongoDB you need to use the sort() method . The method accepts a document containing a list of fields and their sort order. 1 and -1 are used to specify sort order. 1 is used in ascending order and -1 in descending order.

Syntax

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

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

example

Consider a collection myycol that has 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 will display documents 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" } >



Note that if you don't specify a sort preference, then the sort() method will display the documents in ascending order.