MongoDB - Sort Records

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

Syntax:

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



The $sort stage has the following prototype form:

{ $sort: { <field1>: <sort order>, <field2>: <sort order> ... } }



$sort takes a document that specifies the field(s) to sort by and the respective sort order. <sort order> can have one of the following values:
1 to specify ascending order.
-1 to specify descending order.

{ $meta: "textScore" } to sort by the computed textScore metadata in descending order.