> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

# cursor.sort() (mongosh method)

## Definition

**Important: mongosh Method**

This page documents a [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) method. This is *not* the documentation for a language-specific driver, such as Node.js.

For MongoDB API drivers, refer to the language-specific [MongoDB driver documentation.](https://www.mongodb.com/docs/drivers/)

Specifies the order in which the query returns matching documents. You must apply [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) to the cursor before retrieving any documents from the database.

## Compatibility

This method is available in deployments hosted in the following environments:

- [MongoDB Atlas](https://www.mongodb.com/docs/atlas): The fully managed service for MongoDB deployments in the cloud

**Note:**

This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see [Unsupported Commands.](https://www.mongodb.com/docs/atlas/unsupported-commands/)

- [MongoDB Enterprise](https://www.mongodb.com/docs/manual/administration/install-enterprise.md#std-label-install-mdb-enterprise): The subscription-based, self-managed version of MongoDB

- [MongoDB Community](https://www.mongodb.com/docs/manual/administration/install-community.md#std-label-install-mdb-community-edition): The source-available, free-to-use, and self-managed version of MongoDB

## Syntax

The [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) method has the following parameter:

| Parameter | Type | Description |
| --- | --- | --- |
| `sort` | document | A document that defines the sort order of the result set. |

The `sort` parameter contains field and value pairs, in the following form:

```javascript
{ field: value }
```

The sort document can specify [ascending or descending sort on existing fields](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#std-label-sort-asc-desc) or [sort on text score metadata.](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#std-label-sort-metadata)

## Behavior

### Limits

- You can sort on a maximum of 32 keys.

- Providing a sort pattern with duplicate fields causes an error.

### Sort Consistency

MongoDB does not store documents in a collection in a particular order. When sorting on a field which contains duplicate values, documents containing those values may be returned in any order.

The `$sort` operation is not a "stable sort," which means that documents with equivalent sort keys are not guaranteed to remain in the same relative order in the output as they were in the input.

If the field specified in the sort criteria does not exist in two documents, then the value on which they are sorted is the same. The two documents may be returned in any order.

If consistent sort order is desired, include at least one field in your sort that contains unique values. The easiest way to guarantee this is to include the `_id` field in your sort query.

The following examples use the `restaurants` collection in the `sample_restaurants` database, which contains documents with a `borough` field that has duplicate values.

The following command uses the [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) method to sort on the `borough` field:

```javascript
db.getSiblingDB("sample_restaurants").restaurants.find(
   { borough: { $in: [ "Brooklyn", "Manhattan" ] } },
   { name: 1, borough: 1 }
).sort( { borough: 1 } ).limit( 5 )

```

In this example, sort order may be inconsistent, since the `borough` field contains duplicate values. Documents are returned in alphabetical order by `borough`, but the order of those documents with duplicate values for `borough` might not be the same across multiple executions of the same sort.

To achieve a *consistent sort*, add a field which contains exclusively unique values to the sort. The following command uses the [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) method to sort on both the `borough` field and the `_id` field:

```javascript
db.getSiblingDB("sample_restaurants").restaurants.find(
   { borough: { $in: [ "Brooklyn", "Manhattan" ] } },
   { name: 1, borough: 1 }
).sort( { borough: 1, _id: 1 } ).limit( 5 )

```

**Output:**

```javascript
[
  {
    _id: ObjectId('5eb3d668b31de5d588f4292a'),
    borough: 'Brooklyn',
    name: 'Riviera Caterer'
  },
  {
    _id: ObjectId('5eb3d668b31de5d588f4292b'),
    borough: 'Brooklyn',
    name: "Wilken'S Fine Food"
  },
  {
    _id: ObjectId('5eb3d668b31de5d588f4292d'),
    borough: 'Brooklyn',
    name: "Wendy'S"
  },
  {
    _id: ObjectId('5eb3d668b31de5d588f42931'),
    borough: 'Brooklyn',
    name: 'Regina Caterers'
  },
  {
    _id: ObjectId('5eb3d668b31de5d588f42932'),
    borough: 'Brooklyn',
    name: 'Taste The Tropics Ice Cream'
  }
]

```

Since the `_id` field is always guaranteed to contain exclusively unique values, the returned sort order will always be the same across multiple executions of the same sort.

**Important:**

When sorting by a nonexistent field, MongoDB does not guarantee any particular output ordering. The behavior in these cases may change from version to version.

### Ascending/Descending Sort

Specify in the sort parameter the field or fields to sort by and a value of `1` or `-1` to specify an ascending or descending sort respectively.

The following operation sorts the documents from the `movies` collection in the `sample_mflix` database, first by the `year` field in descending order and then by the `title` field in ascending order:

```javascript
db.movies.find(
   { year: { $type: "int" } },
   { _id: 0, title: 1, year: 1 }
).sort( { year: -1, title: 1 } ).limit( 5 )

```

**Output:**

```javascript
[
  { title: 'The Masked Saint', year: 2016 },
  { title: '(T)ERROR', year: 2015 },
  { title: '11 Minutes', year: 2015 },
  { title: '13 Minutes', year: 2015 },
  { title: '3 1/2 Minutes, Ten Bullets', year: 2015 }
]

```

When comparing values of different [BSON types](https://www.mongodb.com/docs/manual/reference/bson-types.md#std-label-bson-types) in sort operations, MongoDB uses the following comparison order, from lowest to highest:

1. MinKey (internal type)

2. Null

3. Numbers (ints, longs, doubles, decimals)

4. Symbol, String

5. Object

6. Array

7. BinData

8. ObjectId

9. Boolean

10. Date

11. Timestamp

12. Regular Expression

13. JavaScript Code

14. JavaScript Code with Scope

15. MaxKey (internal type)

For details on the comparison/sort order for specific types, see [Comparison/Sort Order.](https://www.mongodb.com/docs/manual/reference/bson-type-comparison-order.md#std-label-bson-types-comparison-order)

### Text Score Metadata Sort

**Note:**

`$text` provides text query capabilities for self-managed (non-Atlas) deployments. For data hosted on MongoDB, MongoDB also offers an improved full-text query solution, [MongoDB Search.](https://www.mongodb.com/docs/atlas/atlas-search/)

If you use [`$text`](https://www.mongodb.com/docs/manual/reference/operator/query/text.md#mongodb-query-op.-text), you can sort by descending relevance score using the [`{ $meta: "textScore" }`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#mongodb-expression-exp.-meta) expression.

The following sample document specifies a descending sort by the `"textScore"` metadata:

```javascript
db.users.find(
   { $text: { $search: "operating" } },
   { score: { $meta: "textScore" }}
).sort({ score: { $meta: "textScore" } })
```

The `"textScore"` metadata sorts in descending order.

For more information, see [`$meta`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#mongodb-expression-exp.-meta) for details.

### Sort by an Array Field

When MongoDB sorts documents by an array-value field, the [sort key](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-sort-key) depends on whether the sort is ascending or descending:

- In an ascending sort, the sort key is the lowest value in the array.

- In a descending sort, the sort key is the highest value in the array.

The query filter does not affect sort key selection.

For example, the following queries use the `movies` collection in the `sample_mflix` database to sort documents by the `genres` array field in ascending and descending order:

```javascript
db.movies.find(
   { genres: { $exists: true, $ne: [] } },
   { _id: 0, title: 1, genres: 1 }
).sort( { genres: 1 } ).limit( 3 )

```

```javascript
db.movies.find(
   { genres: { $exists: true, $ne: [] } },
   { _id: 0, title: 1, genres: 1 }
).sort( { genres: -1 } ).limit( 3 )

```

In the ascending sort, MongoDB uses the first genre alphabetically as the sort key. In the descending sort, MongoDB uses the last genre alphabetically as the sort key.

#### Filter and Sort by an Array Field

When you filter and sort by a field that contains an array, the filter does not affect the value used as the [sort key](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-sort-key). The sort always considers all array values as potential sort keys.

For example, the following query finds movies with a genre that is greater than `"P"` and sorts the results in ascending order:

```javascript
db.movies.find(
   { genres: { $gt: "P" } },
   { _id: 0, title: 1, genres: 1 }
).sort( { genres: 1 } ).limit( 3 )

```

The sort is ascending, which means that the sort key is the lowest value in the `genres` array, even if that value does not match the filter `{ genres: { $gt: "P" } }`.

**Tip: Sort only by Matched Values**

To only consider matched values as potential sort keys, you can generate a new field containing the matched values and sort on that field. For more information, see these pipeline stages and expressions:

- [`$addFields`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/addfields.md#mongodb-pipeline-pipe.-addFields)

- [`$filter`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/filter.md#mongodb-expression-exp.-filter)

- [`$sort`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#mongodb-pipeline-pipe.-sort)

### Sort and Index Use

If the collection has an index that includes the sort fields, MongoDB can use that index to obtain the results of a sort operation. In [`$or`](https://www.mongodb.com/docs/manual/reference/operator/query/or.md#mongodb-query-op.-or) queries, MongoDB may use multiple indexes to support a single sort operation, because each clause of the `$or` expression can use its own index.

If MongoDB cannot use an index or indexes to obtain the sort order, MongoDB must perform an in-memory sort operation on the data.

Sort operations that use an index often have better performance than in-memory sorts. For more information on creating indexes to support sort operations, see [Use Indexes to Sort Query Results.](https://www.mongodb.com/docs/manual/tutorial/sort-results-with-indexes.md#std-label-sorting-with-indexes)

To check if MongoDB must perform an in-memory sort, append [`cursor.explain()`](https://www.mongodb.com/docs/manual/reference/method/cursor.explain.md#mongodb-method-cursor.explain) to the query and check the [explain results](https://www.mongodb.com/docs/manual/reference/explain-results.md#std-label-explain-results). If the query plan contains a `SORT` stage, then MongoDB must perform an in-memory sort operation.

To prevent in-memory sorts from consuming too much memory:

- Create an index to support the sort operation. See [Use Indexes to Sort Query Results](https://www.mongodb.com/docs/manual/tutorial/sort-results-with-indexes.md) for more information and examples.

- Limit the amount of data to sort by using [`cursor.limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) with [`cursor.sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort). See [Limit Results](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#std-label-sort-limit-results) for more information and examples.

**See also:**

[Memory Limits on Sort Operations](https://www.mongodb.com/docs/manual/reference/limits.md#mongodb-limit-Sort-Operations)

### Limit Results

You can use [`sort()`](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#mongodb-method-cursor.sort) in conjunction with [`limit()`](https://www.mongodb.com/docs/manual/reference/method/cursor.limit.md#mongodb-method-cursor.limit) to return the first (in terms of the sort order) `k` documents, where `k` is the specified limit.

If MongoDB cannot obtain the sort order with an index scan, then MongoDB uses a top-k sort algorithm. This algorithm buffers the first `k` results (or last, depending on the sort order) seen so far by the underlying index or collection access. If the memory footprint of these `k` results exceeds 100 megabytes, MongoDB automatically writes temporary files to disk unless the query specifies [`cursor.allowDiskUse()`](https://www.mongodb.com/docs/manual/reference/method/cursor.allowdiskuse.md#mongodb-method-cursor.allowDiskUse) with a value of `false` (in which case, the query fails).

**See also:**

[Memory Limits on Sort Operations](https://www.mongodb.com/docs/manual/reference/limits.md#mongodb-limit-Sort-Operations)

### Interaction with Projection

When an operation both sorts *and* [projects](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-projection) with the same fields, MongoDB sorts on the original field values before applying the projection.

## Examples

The following examples use the `movies` collection in the `sample_mflix` database.

The following query returns movies without specifying a sort order:

```javascript
db.movies.find(
   {},
   { _id: 0, title: 1, runtime: 1 }
).limit( 3 )

```

The query returns the documents in indeterminate order.

The following query specifies a sort on the `runtime` field in descending order:

```javascript
db.movies.find(
   {},
   { _id: 0, title: 1, runtime: 1 }
).sort( { runtime: -1 } ).limit( 5 )

```

**Output:**

```javascript
[
  { title: 'Centennial', runtime: 1256 },
  { title: 'Baseball', runtime: 1140 },
  { title: 'Taken', runtime: 877 },
  { title: 'Space', runtime: 780 },
  { title: 'Reilly: Ace of Spies', runtime: 720 }
]

```

The following query sorts first by the `imdb.rating` field in ascending order, and then by the `title` field in ascending order:

```javascript
db.movies.find(
   { "imdb.rating": { $type: "double" } },
   { _id: 0, title: 1, "imdb.rating": 1 }
).sort( { "imdb.rating": 1, title: 1 } ).limit( 5 )

```

**Output:**

```javascript
[
  {
    title: "Justin Bieber's Believe",
    imdb: { rating: 1.6 }
  },
  {
    title: 'Justin Bieber: Never Say Never',
    imdb: { rating: 1.6 }
  },
  {
    title: 'Saving Christmas',
    imdb: { rating: 1.6 }
  },
  {
    title: 'Disaster Movie',
    imdb: { rating: 1.9 }
  },
  {
    title: 'Superbabies: Baby Geniuses 2',
    imdb: { rating: 1.9 }
  }
]

```

## Return in Natural Order

The [`$natural`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-operator-metaOp.-natural) parameter returns items according to their [natural order](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-natural-order) within the database. This ordering is an internal implementation feature, and you should not rely on any particular ordering of the documents.

**Note:**

Prior to MongoDB 7.0, [`$natural`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-operator-metaOp.-natural) accepts incorrect type values, such as `0`, `NaN`, "X", and `-0.01`. After MongoDB 7.0, if you pass any value other than `1` and `-1` to [`$natural`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-operator-metaOp.-natural), MongoDB returns an error.

### Index Use

Queries that include a sort by [`$natural`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-operator-metaOp.-natural) order do **not** use indexes to fulfill the query predicate with the following exception: If the query predicate is an equality condition on the `_id` field `{ _id: <value> }`, then the query with the sort by [`$natural`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-operator-metaOp.-natural) order can use the `_id` index.

**See also:**

[`$natural`](https://www.mongodb.com/docs/manual/reference/method/cursor.hint.md#mongodb-operator-metaOp.-natural)
