MongoDB sort() method

Specifies the order in which the query returns matching documents. You must apply sort() to the cursor before retrieving any documents from the database.

Syntax

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

The sort() method has a document that defines the sort order of the result set.

							
							
{ field: value }

Ascending/Descending Sort

Specify in the sort parameter the field or fields to sort by and a value of 1 or -1 to specify an ascending or descending sort respectively.

The following sample document specifies a descending sort by the age field and then an ascending sort by the posts field:


{ age : -1, posts: 1 }

When comparing values of different BSON types, MongoDB uses the following comparison order, from lowest to highest:

  • MinKey (internal type)
  • Null
  • Numbers (ints, longs, doubles)
  • Symbol, String
  • Object
  • Array
  • BinData
  • ObjectId
  • Boolean
  • Date
  • Timestamp
  • Regular Expression
  • MaxKey (internal type)