cursor.sort()

Definition

cursor.sort(sort)

Controls the order that the query returns matching documents. For each field in the sort document, if the field’s corresponding value is positive, then sort() returns query results in ascending order for that attribute. If the field’s corresponding value is negative, then sort() returns query results in descending order.

The sort() method has the following parameter:

Parameter Type Description
sort document A document that defines the sort order of the result set.

The sort parameter contains field and value pairs, in the following form:

{ field: value }
  • field is the field by which to sort documents.
  • value is either 1 for ascending or -1 for descending.

Note

You must apply limit() to the cursor before retrieving any documents from the database.

Examples

The following query returns all documents in collection sorted by the age field in descending order.

db.collection.find().sort( { age: -1 } );

The following query specifies the sort order using the fields from a sub-document name. The query sorts first by the last field and then by the first field. The query sorts both fields in ascending order:

db.bios.find().sort( { 'name.last': 1, 'name.first': 1 } )

Limit Results

Unless you have an index for the specified key pattern, use sort() in conjunction with limit() to avoid requiring MongoDB to perform a large, in-memory sort. limit() increases the speed and reduces the amount of memory required to return this query by way of an optimized algorithm.

Warning

The sort function requires that the entire sort be able to complete within 32 megabytes. When the sort option consumes more than 32 megabytes, MongoDB will return an error. Use limit(), or create an index on the field that you’re sorting to avoid this error.

Return Natural Order

The $natural parameter returns items according to their order on disk. Consider the following query:

db.collection.find().sort( { $natural: -1 } )

This will return documents in the reverse of the order on disk. Typically, the order of documents on disks reflects insertion order, except when documents move internal because of document growth due to update operations.

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

  1. MinKey (internal type)
  2. Null
  3. Numbers (ints, longs, doubles)
  4. Symbol, String
  5. Object
  6. Array
  7. BinData
  8. ObjectID
  9. Boolean
  10. Date, Timestamp
  11. Regular Expression
  12. MaxKey (internal type)

Note

MongoDB treats some types as equivalent for comparison purposes. For instance, numeric types undergo conversion before comparison.