$orderby¶
-
$orderby¶ The
$orderbyoperator sorts the results of a query in ascending or descending order.The
mongoshell 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
collectionsorted by theagefield in descending order. Specify a value to$orderbyof 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
$orderbyin conjunction with$maxScanand/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.