- Reference >
- JavaScript Methods >
- cursor.sort()
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, thensort()
returns query results in ascending order for that attribute: if the field’s corresponding value is negative, thensort()
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:
Here, the query returns all documents in
collection
sorted by theage
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 withcursor.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: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:
- MinKey (internal type)
- Null
- Numbers (ints, longs, doubles)
- Symbol, String
- Object
- Array
- BinData
- ObjectID
- Boolean
- Date, Timestamp
- Regular Expression
- MaxKey (internal type)
Note
MongoDB treats some types as equivalent for comparison purposes. For instance, numeric types undergo conversion before comparison.