This version of the documentation is archived and no longer supported.



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.

Unless you have an index for the specified key pattern, use $orderby in conjunction with $maxScan and/or cursor.limit() to avoid requiring MongoDB to perform a large in-memory sort. The cursor.limit() increases the speed and reduces the amount of memory required to return this query by way of an optimized algorithm.

←   $natural $query  →