$orderby
Deprecated since v3.2
Starting in v3.2, the $orderby
operator is deprecated in themongo
shell. In the mongo
shell,use cursor.sort()
instead.
The $orderby
operator sorts the results of a query inascending or descending order.
The mongo
shell provides the cursor.sort()
method:
- db.collection.find().sort( { age: -1 } )
You can also specify the option in either of the following forms:
- db.collection.find()._addSpecial( "$orderby", { age : -1 } )
- db.collection.find( { $query: {}, $orderby: { age : -1 } } )
These examples return all documents in the collection namedcollection
sorted by the age
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.
Behavior
The sort function requires that the entire sort be able to completewithin 32 megabytes. When the sort option consumes more than 32megabytes, MongoDB will return an error.
To avoid this error, create an index to support the sort operation oruse $orderby
in conjunction with cursor.maxTimeMS()
and/or cursor.limit()
. The cursor.limit()
increasesthe speed and reduces the amount of memory required to return thisquery by way of an optimized algorithm. The specified limit must resultin a number of documents that fall within the 32 megabyte limit.