$orderby¶
-
$orderby
¶ The
$orderby
operator sorts the results of a query in ascending or descending order.The
mongo
shell provides thecursor.sort()
method:You can also specify the option in either of the following forms:
These examples return all documents in the collection named
collection
sorted by theage
field in descending order. Specify a value to$orderby
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
$orderby
in conjunction with$maxScan
and/orcursor.limit()
to avoid requiring MongoDB to perform a large in-memory sort. Thecursor.limit()
increases the speed and reduces the amount of memory required to return this query by way of an optimized algorithm.