The $orderby operator sorts the results of a query in ascending 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 named collection 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.


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.

To avoid this error, create an index to support the sort operation or use $orderby in conjunction with $maxScan and/or cursor.limit(). The cursor.limit() increases the speed and reduces the amount of memory required to return this query by way of an optimized algorithm. The specified limit must result in a number of documents that fall within the 32 megabyte limit.

←   $min $returnKey  →

Was this page helpful?

Yes No

Thank you for your feedback!

We're sorry! You can Report a Problem to help us improve this page.