Sort () method
To sort documents in MongoDB, you need to use the sort () method. The sort () method accepts a document that contains a list of fields together with their sort order. To specify sort order 1 and-1. 1 is used in ascending order, and-1 for descending order.
Grammar:
The basic syntax for the sort () method is as follows
>db. Collection_name. Find(). Sort({KEY:1})
Example
Consider the collection Myycol with the following data
{ "_ID" : ObjectId(5983548781331adf45ec5), "Title":"MongoDB Overview"}{ "_id" : objectid ( 5983548781331adf45ec6 "title" : "NoSQL Overview" }{ "_id" : objectid5983548781331adf45ec7 " Title ":" Yiibai Overview "}
The following example shows a file sorted in descending order by title.
>Db.MyCol.Find({},{ "title" :1,_id :0}). sort ({:-< span class= "lit" >1< Span class= "pun") { "title" : "tutorials Yiibai Overview" }{ "title" : "NoSQL Overview" } { "title" : MongoDB Overview "}>
Note that if sort precedence is not specified, then the sort () method displays the document in ascending order.
MongoDB QuickStart (11)