Docs Menu

Docs HomeMongoDB Manual


On this page

  • Behavior


Deprecated since v3.2

Starting in v3.2, the $orderby operator is deprecated in mongosh. In mongosh, use cursor.sort() instead.

The $orderby operator sorts the results of a query in ascending or descending order.

mongosh 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.

Since indexes contain ordered records, MongoDB can obtain the results of a sort from an index which includes the sort fields. MongoDB may use multiple indexes to support a sort operation if the sort uses the same indexes as the query predicate.

If MongoDB cannot use an index or indexes to obtain the sort order, MongoDB must perform a blocking sort operation on the data. A blocking sort indicates that MongoDB must consume and process all input documents to the sort before returning results. Blocking sorts do not block concurrent operations on the collection or database.

Sort operations that use an index often have better performance than blocking sorts. For more information on creating indexes to support sort operations, see Use Indexes to Sort Query Results.

If MongoDB requires using more than 100 megabytes of system memory for the blocking sort operation, MongoDB returns an error unless the query specifies cursor.allowDiskUse() (New in MongoDB 4.4). allowDiskUse() allows MongoDB to use temporary files on disk to store data exceeding the 100 megabyte system memory limit while processing a blocking sort operation.

To avoid this error, create an index to support the sort operation or use $orderby in conjunction with cursor.maxTimeMS() 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 100 megabyte limit.

←  $min$query →

On this page

Share Feedback