- Reference >
mongo
Shell Methods >- Cursor Methods >
- cursor.sort()
cursor.sort()¶
On this page
Definition¶
-
cursor.
sort
(sort)¶ mongo
Shell MethodThis page documents the
mongo
shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.Specifies the order in which the query returns matching documents. You must apply
sort()
to the cursor before retrieving any documents from the database.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:The sort document can specify ascending or descending sort on existing fields or sort on text score metadata.
Behaviors¶
Result Ordering¶
Unless you specify the sort()
method or use the
$near
operator, MongoDB does not guarantee the order of
query results.
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 operation sorts the documents first by the age
field
in descending order and then by the posts
field in ascending order:
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, decimals)
- Symbol, String
- Object
- Array
- BinData
- ObjectId
- Boolean
- Date
- Timestamp
- Regular Expression
- MaxKey (internal type)
For details on the comparison/sort order for specific types, see Comparison/Sort Order.
Text Score Metadata Sort¶
For a $text
search, you can sort by descending relevance score
using the { $meta: "textScore" }
expression.
The following sample document specifies a descending sort by the
"textScore"
metadata:
The "textScore"
metadata sorts in descending order.
For more information, see $meta
for details.
Sort and Index Use¶
MongoDB can obtain the results of a sort operation from an index which includes the sort fields. MongoDB may use multiple indexes to support a sort operation if the sort uses the same indexes as the query predicate.
If MongoDB cannot use an index or indexes to obtain the sort order, MongoDB must perform a blocking sort operation on the data. A blocking sort indicates that MongoDB must consume and process all input documents to the sort before returning results. Blocking sorts do not block concurrent operations on the collection or database.
Sort operations that use an index often have better performance than blocking sorts. For more information on creating indexes to support sort operations, see Use Indexes to Sort Query Results.
If MongoDB requires using more than 100 megabytes of system memory for
the blocking sort operation, MongoDB returns an error unless the query
specifies cursor.allowDiskUse()
(New in MongoDB 4.4).
allowDiskUse()
allows MongoDB to use temporary files
on disk to store data exceeding the 100 megabyte system memory limit
while processing a blocking sort operation.
To check if MongoDB must perform a blocking sort, append
cursor.explain()
to the query and check the
explain results. If the query plan
contains a SORT
stage, then MongoDB must perform a
blocking sort operation subject to the 100 megabyte memory limit.
To prevent blocking sorts from consuming too much memory:
- Create an index to support the sort operation. See Use Indexes to Sort Query Results for more information and examples.
- Limit the amount of data to sort by using
cursor.limit()
withcursor.sort()
. See Limit Results for more information and examples.
See also
Limit Results¶
You can use sort()
in conjunction with
limit()
to return the first (in terms of the sort
order) k
documents, where k
is the specified limit.
If MongoDB cannot obtain the sort order via an index scan, then MongoDB
uses a top-k sort algorithm. This algorithm buffers the first k
results (or last, depending on the sort order) seen so far by the
underlying index or collection access. If at any point the memory
footprint of these k
results exceeds 100 megabytes, the query will
fail unless the query specifies cursor.allowDiskUse()
(New in MongoDB 4.4).
See also
Interaction with Projection¶
When a set of results are both sorted and projected, the MongoDB query engine will always apply the sorting first.
Examples¶
A collection orders
contain the following documents:
The following query, which returns all documents from the orders
collection, does not specify a sort order:
The query returns the documents in indeterminate order:
The following query specifies a sort on the amount
field in
descending order.
The query returns the following documents, in descending order of
amount
:
The following query specifies the sort order using the fields from an
embedded document item
. The query sorts first by the category
field
in ascending order, and then within each category
, by the type
field in ascending order.
The query returns the following documents, ordered first by the
category
field, and within each category, by the type
field:
Return in Natural Order¶
The $natural
parameter returns items according to their
natural order within the database. This ordering is an internal
implementation feature, and you should not rely on any particular
ordering of the documents.