Navigation
This version of the documentation is archived and no longer supported.

cursor.sort()

cursor.sort(sort)
Parameters:
  • sort – A document whose fields specify the attributes on which to sort the result set.

Append the sort() method to a cursor to control 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.

Note

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

Consider the following example:

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

Here, the query returns all documents in collection sorted by the age field in descending order. Specify a value of negative one (e.g. -1), as above, to sort in descending order or a positive value (e.g. 1) to sort in ascending order.

Unless you have an index for the specified key pattern, use cursor.sort() in conjunction with cursor.limit() to avoid requiring MongoDB to perform a large, in-memory sort. cursor.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 cursor.limit(), or create an index on the field that you’re sorting to avoid this error.

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.