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

# Sort MongoDB Search Results

## Overview

MongoDB Search allows you to sort the results in ascending or descending order on fields that you define in your MongoDB Search index. You can sort by the following field types using the `sort` option:

- `boolean`

- `date`

- `number` (integer, float, and double values)

- `objectId`

- `uuid`

- `string` (indexed as the [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) type)

You can also sort by the score of the documents in the results and by [null values.](https://www.mongodb.com/docs/search/query/sort.md#std-label-fts-sort-null)

### `sort` Option Compatibility

Atlas supports both non-sharded and sharded sort queries on all major and minor releases for MongoDB 7.0 and later versions.

### `sort` Option Limitations

- You can't sort on fields of [embeddedDocuments](https://www.mongodb.com/docs/search/indexes/field-types/embedded-documents-type.md#std-label-bson-data-types-embedded-documents) type.

- You can't use the `sort` option with the deprecated [knnBeta](https://www.mongodb.com/docs/search/query/operators-collectors/knn-beta.md#std-label-knn-beta-ref) operator.

### Usage

To sort your MongoDB Search results, you must do the following:

1. Create a MongoDB Search index on the fields to sort the results by.

   To sort on `boolean`, `date`, `number`, `UUID`, and `objectId` fields, use dynamic or static mappings. To sort on string fields, you must use [static mappings](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-static-dynamic-mappings) to index the field as the `token` type.

2. Create and run your query with the `sort` option against the fields you defined in the index for sorting. To learn more, see [Syntax.](https://www.mongodb.com/docs/search/query/sort.md#std-label-sort-syntax-ref)

### Behavior

#### Sort by Boolean, Date, Numeric, UUID, ObjectId, or String Field

The `sort` option takes a document that specifies the fields to sort by and the respective sort order. MongoDB Search follows the [MongoDB comparison order](https://www.mongodb.com/docs/manual/reference/bson-type-comparison-order.md#std-label-bson-types-comparison-order) for the supported data types. It treats UUID values like `BinData`. To learn more, see [non-existent fields.](https://www.mongodb.com/docs/manual/reference/bson-type-comparison-order/#non-existent-fields)

You can specify the following sort order to sort your results by:

| `1` | Sort in ascending order. When you sort in ascending order, MongoDB Search returns documents with missing values before documents with values. |
| --- | --- |
| `-1` | Sort in descending order. |

#### Sort by Score And a Unique Field

You can also sort by score in ascending or descending order. The `sort` option takes a document that specifies the [`$meta`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#mongodb-expression-exp.-meta) expression, which requires the `searchScore` value.

**Example:**

Suppose your application allows users to skip to the last page of the search results. The following example sorts the results by score in ascending order so that the document with the lowest score displays at the top of the results:

```json
sort: {score: {$meta: "searchScore", order: 1}}
```

You can use `sort` to also ensure that the results have a determined order when multiple documents in the results have identical scores. For example, if you sort the results by a unique field, such as a date field named `lastUpdated` as shown in the following example, MongoDB Search returns results with identical scores in a determined order:

**Example:**

```text
sort: {score: {$meta: "searchScore"}, lastUpdated: 1}
```

However, if you don't specify a unique field to sort the results by, MongoDB Search returns the results sorted by score in descending order. MongoDB Search returns results with identical scores or values in an arbitrary order. The following example doesn't sort the results by a unique field.

**Example:**

```shell
sort: {score: {$meta: "searchScore"}}
```

To learn more, see [Score the Documents in the Results.](https://www.mongodb.com/docs/search/query/score/overview.md#std-label-scoring-ref)

#### Sort Arrays

MongoDB Search flattens the arrays for sorting.

**Example:**

Consider the following array:

```shell
[4, [1, [8,5], 9], 2]
```

MongoDB Search flattens the preceding array similar to the following:

```shell
4, 1, 8, 5, 9, 2
```

For an ascending sort, MongoDB Search uses `1` to compare the array to other values. For a descending sort, MongoDB Search uses `9` to compare the array to other values.

When comparing with elements inside an array:

- For an ascending sort, MongoDB Search compares the smallest elements of the array or performs a less than (`<`) comparison.

  **Example:**

  MongoDB Search sorts results in the following order if you sort by numbers in ascending order:

  ```shell
  -20
  [-3, 12] // <- -3 comes before 5.
  5
  [6, 18]  // <- 6 comes after 5.
  13
  14
  ```

- For a descending sort, MongoDB Search compares the largest elements of the array or performs a greater than (`>`) comparison.

  **Example:**

  MongoDB Search sorts results in the following order if you sort by numbers in descending order:

  ```shell
  [6, 18]  // <- 18 comes before 14.
  14
  13
  [-3, 12] // <- 12 comes after 13.
  5
  -20
  ```

#### Sort Arrays with Multiple Types

When sorting over array fields that contain values of multiple BSON (Binary Javascript Object Notation) types, MongoDB Search selects a representative element from the array to use for comparison according to the [MongoDB comparison and sort order](https://www.mongodb.com/docs/manual/reference/bson-type-comparison-order.md#std-label-bson-types-comparison-order) by default.

- For an ascending sort, MongoDB Search uses the element with the lowest BSON (Binary Javascript Object Notation) type.

- For a descending sort, MongoDB Search uses the element with the highest BSON (Binary Javascript Object Notation) type.

If there are multiple values of the same BSON (Binary Javascript Object Notation) type in the array, standard sort behavior for the selected type applies.

**Example:**

Consider the following array:

```shell
[ 'foo', null, 15, true, false ]
```

- For an ascending sort, MongoDB Search uses `null`, as it is the lowest [supported](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-bson-data-types) BSON (Binary Javascript Object Notation) type.

- For a descending sort, MongoDB Search uses `true`, as it is the highest BSON (Binary Javascript Object Notation) type in the array and MongoDB Search ranks `true` values above `false` values.

However, if you set `noData: highest` in your `sort` [syntax](https://www.mongodb.com/docs/search/query/sort.md#std-label-sort-syntax-ref), MongoDB Search considers null and missing values as the highest BSON (Binary Javascript Object Notation) type. For the example array, the following behavior applies:

- For an ascending sort, MongoDB Search uses `15`, as it is now the lowest BSON (Binary Javascript Object Notation) type in the array.

- For a descending sort, MongoDB Search uses `null`, as it is now the highest BSON (Binary Javascript Object Notation) type in the array.

To learn more, see [Sort by Null and Missing Values.](https://www.mongodb.com/docs/search/query/sort.md#std-label-fts-sort-null)

For an example, see [Sort on Multi-Typed Arrays.](https://www.mongodb.com/docs/search/query/sort.md#std-label-fts-sort-eg-null-multiple-types)

#### Sort by Null and Missing Values

MongoDB Search treats null values as equal to missing and empty values, and the order of documents with these values is non-deterministic when sorting.

By default, MongoDB Search follows the [MongoDB comparison and sort order](https://www.mongodb.com/docs/manual/reference/bson-type-comparison-order.md#std-label-bson-types-comparison-order) and considers null values as lower than all other [supported](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-bson-data-types) BSON (Binary Javascript Object Notation) types. Therefore, null values appear at the top of the results during an ascending sort and at the bottom during a descending sort.

To configure where null values appear in the results, specify the `noData` field in your `sort` [syntax](https://www.mongodb.com/docs/search/query/sort.md#std-label-sort-syntax-ref). The `noData` field takes the following values:

- `lowest` (default): Sets null values as the lowest BSON (Binary Javascript Object Notation) type during sorting. Sorts null values at the top of the results during an ascending sort and at the bottom during a descending sort.

- `highest`: Sets null values as the highest BSON (Binary Javascript Object Notation) type during sorting. Sorts null values at the bottom of the results during an ascending sort and at the top during a descending sort.

**Note:**

The same behavior applies when sorting on [arrays with multiple types](https://www.mongodb.com/docs/search/query/sort.md#std-label-fts-sort-arrays-multiple-types) that contain null or missing values.

For examples, see [Sort by Null Values](https://www.mongodb.com/docs/search/query/sort.md#std-label-fts-sort-eg-null) and [Sort on Multi-Typed Arrays.](https://www.mongodb.com/docs/search/query/sort.md#std-label-fts-sort-eg-null-multiple-types)

#### Sort on Embedded Documents Array Fields

To sort the parent documents by an embedded document field, you must do the following:

- Index the parents of the embedded document child field as the [document](https://www.mongodb.com/docs/search/indexes/field-types/document-type.md#std-label-bson-data-types-document) type.

- Index the child field with string values within the embedded document as the [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) type. For child fields with number and date values, enable [dynamic mapping](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-static-dynamic-mappings) to index those fields automatically.

MongoDB Search sorts on parent documents only. It doesn't sort the child fields within an array of documents. For an example, see [Sort Example.](https://www.mongodb.com/docs/search/query/operators-collectors/embedded-document.md#std-label-embedded-document-query-examples)

### Considerations

#### Consistency

MongoDB Search indexes are eventually [consistent](https://www.mongodb.com/docs/search/performance/index-performance.md#std-label-index-eventual-consistency-and-latency), and values returned in results might be different from values used in sorting.

#### Performance

This feature optimizes queries that use [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) with [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) as a subsequent stage. If MongoDB Search needs to sort all documents in the collection, the response might be slow.

#### Scoring

MongoDB Search returns [scores](https://www.mongodb.com/docs/search/query/score/overview.md#std-label-scoring-ref) for all documents in the results. However, you might see higher scoring documents after lower scoring documents because the order of documents in the results is based on the sort criteria unless you explicitly sort by score.

## Syntax

`sort` has the following syntax:

```json
{
  "$search": {
    "index": "<index name>", // optional, defaults to "default"
    "<operator>": { // such as "text", "compound", or "phrase"
      <operator-specification>
    },
    "sort": {
      score: {$meta: "searchScore"}, // optional field
      "<field-to-sort>": <sort-order>, // 1 or -1, or a document
      ...
    }
  }
}
```

| Parameter | Description |
| --- | --- |
| `score` | Optional. Determines whether to sort by the search score. To learn more, see [Sort by Score And a Unique Field.](https://www.mongodb.com/docs/search/query/sort.md#std-label-fts-sort-score-unique-field) |
| `<field-to-sort>` | Required. The name of the field to sort by. |
| `<sort-order>` | Required. Determines the sort order. Use `1` for ascending order and `-1` for descending order. If you want to specify the [noData](https://www.mongodb.com/docs/search/query/sort.md#std-label-fts-sort-null) field, use a document with the following syntax: `"<field-to-sort>": {
  order: 1 | -1, // required field
  noData: "lowest" | "highest" // optional field
},
...` |

## Examples

The following examples use the `sample_mflix.movies`, `sample_airbnb.listingsAndReview`, or a custom collection named `users`.

### Index Definition

The example queries in this page use either the `sample_mflix.movies`, the `sample_airbnb.listingsAndReview`, or a custom collection. If you create the following indexes on these collections, you can run the sample queries against the indexed fields.

#### movies Collection

The index definition for the `movies` collection specifies the following:

- Index `awards.wins` field as:

  - `number` type for sorting and querying, including running [`facet` (MongoDB Search Operator)](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref) queries

- Index `released` field as:

  - `date` type for sorting and querying, including running [`facet` (MongoDB Search Operator)](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref) queries

- Index `title` field as:

  - `token` type for sorting

  - `string` type for querying

```json
{
  "mappings": {
    "dynamic": true,
    "fields": {
      "awards": {
        "dynamic": false,
        "fields": {
          "wins": [
            {
              "type": "number"
            }
          ]
        },
        "type": "document"
      },
      "released": [
        {
          "type": "date"
        }
      ],
      "title": [{
        "type": "token"
      }, {
        "type": "string"
      }]
    }
  }
}
```

For the preceding index definition, MongoDB Search creates an index named `default` with [static mappings](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-static-dynamic-mappings) on the specified fields.

#### listingsAndReviews Collection

The example queries against the `sample_airbnb.listingsAndReviews` collection use the following index. The index definition specifies dynamic mappings on the fields in the collection:

```json
{
  "mappings": {
    "dynamic": true
  }
}
```

#### users Collection

The `users` collection contains the following documents:

```json
db.users.insertMany([
  {
    "_id": 0,
    "a": UUID("1a324de2-e34b-c87e-f2a1-42ce37ad74ed"),
    "b": "hello",
    "c": ObjectId("507f1f77bcf86cd799439011")
  },
  {
    "_id": 1,
    "a": UUID("3b241101-e2bb-4255-8caf-4136c566a962"),
    "b": "hello",
    "c": true
  },
  {
    "_id": 2,
    "a": UUID("dee11d4e-63c6-4d90-983c-5c9f1e79e96c"),
    "b": "hello",
    "c": "foo"
  },
  {
    "_id": 3,
    "b": "hello",
    "c": UUID("3be11d4e-62cb-4e95-9a3c-5c9f1e56c732")
  },
  {
    "_id": 4,
    "a": UUID("d3c12e1c-c36e-25ed-7c3e-1e7f1e53c752"),
    "b": "hello",
    "c": null
  },
  {
    "_id": 5,
    "a": UUID("d73f181e-cdda-42b4-b844-4d6e172e9bc8"),
    "b": "hello",
    "c": []
  }
  {
    "_id": 6,
    "a": UUID("7eeddf21-b313-4a5c-81c2-c68915daa618"),
    "b": "hello",
  }
])
```

The index definition for the `users` collection specifies the following:

- Dynamically index all the fields except fields named `c`.

- Statically index field named `c` as the following types for sorting:

  - `token`

  - `uuid`

  - `objectId`

  - `boolean`

```json
{
  "mappings": {
    "dynamic": true,
    "fields": {
      "c": [
       { "type": "token" },
       { "type": "uuid" },
       { "type": "objectId" },
       { "type": "boolean" },
       { "type": "number" }
      ]
    }
  }
}
```

For the preceding collection, MongoDB Search creates an index named `default` with the specified mappings on the specified fields.

### Date Search and Sort

The following query shows how to run a [compound](https://www.mongodb.com/docs/search/query/operators-collectors/compound.md#std-label-compound-ref) operator query and sort the results by a date field. It uses the following operators:

- [wildcard](https://www.mongodb.com/docs/search/query/operators-collectors/wildcard.md#std-label-wildcard-ref) operator to search for movie titles that begin with `Summer`.

- [near](https://www.mongodb.com/docs/search/query/operators-collectors/near.md#std-label-near-ref) operator to search for movies that were released in and about five months before or after April 18, 2014.

  **Note:**

  When you use `pivot` on a date field, its unit of measure is in milliseconds. MongoDB Search calculates a score for each document based on how close the date field is to the specified date. To learn more, see [near.](https://www.mongodb.com/docs/search/query/operators-collectors/near.md#std-label-near-ref)

The query uses the following pipeline stages:

- [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage to search the `title` and `released` fields and then sort the results by the `released` field in descending order.

- [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage to limit the output to `5` results.

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

  - Exclude all fields except `title` and `released`.

  - Add a field named `score`.

1. Run the query.

   Copy and paste the following query into the Query Editor, and then click the Search button in the Query Editor.

   ```json
   [
     {
       $search: {
         "compound": {
           "filter": [{
             "wildcard": {
               "query": "Summer*",
               "path": "title"
             }
           }],
           "must": [{
             "near": {
               "pivot": 13149000000,
               "path": "released",
               "origin": ISODate("2014-04-18T00:00:00.000+00:00")
             }
           }]
         },
         "sort": {
           "released": -1,
           "title": 1
         }
       }
     }
   ]
   ```

   **Output:**

   ```text
   SCORE: 0.348105788230896  _id:  "573a13f0f29313caabddaf7a"
     countries: Array
     runtime: 104
     cast: Array
     ...
     title: "Summer Nights"
     ...
     released: 2015-01-28T00:00:00.000+00:00
     ...

   SCORE: 0.5917375683784485  _id:  "573a13e6f29313caabdc673b"
     plot: "25-year-old Iiris and Karoliina have been best friends since childhood…"
     genres: Array
     runtime: 90
     ...
     title: "Summertime"
     ...
     released: 2014-08-01T00:00:00.000+00:00
     ...

   SCORE: 0.9934720396995544  _id:  "573a13eff29313caabdd760c"
     plot: "Erik Sparrow is one of the lucky ones. He's got a good job. He's in a …"
     genres: Array
     runtime: 86
     ...
     title: "Summer of Blood"
     ...
     released: 2014-04-17T00:00:00.000+00:00
     ...

   SCORE: 0.15982933342456818  _id:  "573a13cff29313caabd8ab74"
     plot: "The story of an adult and a teenage couple during a brief summer holid…"
     genres: Array
     countries: Array
     ...
     title: "Summer Games"
     ...
     released: 2012-02-08T00:00:00.000+00:00
     ...

   SCORE: 0.13038821518421173  _id:  "573a13cef29313caabd87f4e"
     plot: "Summer of Goliath is a documentary/fiction hybrid that narrates variou…"
     genres: Array
     runtime: 78
     ...
     title: "Summer of Goliath"
     ...
     released: 2011-07-08T00:00:00.000+00:00
     ...

   SCORE: 0.08124520629644394  _id:  "573a13c7f29313caabd7608d"
     plot: "A student tries to fix a problem he accidentally caused in OZ, a digit…"
     genres: Array
     runtime: 114
     ...
     title: "Summer Wars"
     ...
     released: 2009-08-01T00:00:00.000+00:00

   SCORE: 0.0711759403347969  _id:  "573a13bbf29313caabd54ee6"
     plot: "The life of a public school epitomized by disobedient student Jonah Ta…"
     genres: Array
     runtime: 30
     ...
     title: "Summer Heights High"
     ...
     released: 2008-11-09T00:00:00.000+00:00
     ...

   SCORE: 0.06951779872179031  _id:  "573a13bff29313caabd5f935"
     plot: "On his spring break at the seaside, with his wife and his four year ol…"
     genres: Array
     runtime: 102
     ...
     title: "Summer Holiday"
     ...
     released: 2008-09-19T00:00:00.000+00:00
     ...

   SCORE: 0.05834990739822388  _id:  "573a13c0f29313caabd628ac"
     plot: "Kochi Uehara is a fourth grade student living in the suburb of Tokyo. …"
     genres: Array
     runtime: 138
     ...
     title: "Summer Days with Coo"
     ...
     released: 2007-07-28T00:00:00.000+00:00
     ...

   SCORE: 0.056174591183662415  _id:  "573a13b8f29313caabd4c1d0"
     fullplot: "Country girl Yu Hong leaves her village, her family and her lover to s…"
     genres: Array
     runtime: 158
     ...
     title: "Summer Palace"
     ...
     released: 2007-04-18T00:00:00.000+00:00
     ...
   ```

2. Expand your query results.

   The Search Tester might not display all the fields in the documents it returns. To view all the fields, including the field that you specify in the query path, expand the document in the results.

To run the query in [`mongosh`:](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh)

```js
db.movies.aggregate([
{
  $search: {
    "index": "default",
    "compound": {
      "filter": [{
        "wildcard": {
          "query": "Summer*",
          "path": "title"
        }
      }],
      "must": [{
        "near": {
          "pivot": 13149000000,
          "path": "released",
          "origin": ISODate("2014-04-18T00:00:00.000+00:00")
        }
      }]
    },
    "sort": {
      "released": -1
    }
  }
},
{
  $limit: 5
},
{
  $project: {
    "_id": 0, 
    "title": 1,
    "released": 1,
    "score": {
        "$meta": "searchScore"
    }
  }
}])

```

**Output:**

```json
[
  {
    title: 'Summer Nights',
    released: ISODate("2015-01-28T00:00:00.000Z"),
    score: 0.348105788230896
  },
  {
    title: 'Summertime',
    released: ISODate("2014-08-01T00:00:00.000Z"),
    score: 0.5917375683784485
  },
  {
    title: 'Summer of Blood',
    released: ISODate("2014-04-17T00:00:00.000Z"),
    score: 0.9934720396995544
  },
  {
    title: 'Summer Games',
    released: ISODate("2012-02-08T00:00:00.000Z"),
    score: 0.15982933342456818
  },
  {
    title: 'Summer of Goliath',
    released: ISODate("2011-07-08T00:00:00.000Z"),
    score: 0.13038821518421173
  }
]
```

In MongoDB Compass, configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click Add Stage to add additional stages.

| Pipeline Stage | Query |
| --- | --- |
| `$search` | `{
  "index": "default",
  "compound": {
    "filter": [{
      "wildcard": {
        "query": "Summer*",
        "path": "title"
      }
    }],
    "must": [{
      "near": {
        "pivot": 13149000000,
        "path": "released",
        "origin": ISODate("2014-04-18T00:00:00.000+00:00")
      }
    }]
  },
  "sort": {
    "released": -1
  }
}` |
| `$limit` | `5` |
| `$project` | `{
  _id: 0,
  title: 1,
  released: 1,
  score: { $meta: "searchScore" }
}` |

If you enabled Auto Preview, MongoDB Compass displays the following documents next to the `$limit` pipeline stage:

```javascript
{
  title: 'Summer Nights',
  released: 2015-01-28T00:00:00.000+00:00,
  score: 0.348105788230896
},
{
  title: 'Summertime',
  released: 2014-08-01T00:00:00.000+00:00,
  score: 0.5917375683784485
},
{
  title: 'Summer of Blood',
  released: 2014-04-17T00:00:00.000+00:00,
  score: 0.9934720396995544
},
{
  title: 'Summer Games',
  released: 2012-02-08T00:00:00.000+00:00,
  score: 0.15982933342456818
},
{
  title: 'Summer of Goliath',
  released: 2011-07-08T00:00:00.000+00:00,
  score: 0.13038821518421173
}
```

1. Define the query.

   Replace the contents of the `Program.cs` file with the following code.

   ```csharp
   using MongoDB.Bson;
   using MongoDB.Bson.Serialization.Attributes;
   using MongoDB.Bson.Serialization.Conventions;
   using MongoDB.Driver;
   using MongoDB.Driver.Search;

   public class SortByStrings
   {
       private const string MongoConnectionString = "<connection-string>";

       public static void Main(string[] args)
       {
           // allow automapping of the camelCase database fields to our MovieDocument
           var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
           ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);

           // connect to your Atlas cluster
           var mongoClient = new MongoClient(MongoConnectionString);
           var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
           var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");


           // declare data for compound query
           var originDate = new DateTime(2014, 04, 18, 0, 0, 0, DateTimeKind.Utc);

           // define search options
           var searchOptions = new SearchOptions<MovieDocument>() 
               { 
                   Sort = Builders<MovieDocument>.Sort.Descending(movie => movie.Released),
                   IndexName = "default"
               };
               
           // define and run pipeline
           var results = moviesCollection.Aggregate()
               .Search(Builders<MovieDocument>.Search.Compound()
                   .Filter(Builders<MovieDocument>.Search.Wildcard(movie => movie.Title, "Summer*"))
                   .Must(Builders<MovieDocument>.Search.Near(movie => movie.Released, originDate, 13149000000)), searchOptions)
               .Project<MovieDocument>(Builders<MovieDocument>.Projection
                   .Include(movie => movie.Released)
                   .Include(movie => movie.Title)
                   .Exclude(movie => movie.Id)
                   .MetaSearchScore(movie => movie.Score))
               .Limit(5)
               .ToList();

           // print results
           foreach (var movie in results)
           {
               Console.WriteLine(movie.ToJson());
           }
       }
   }

   [BsonIgnoreExtraElements]
   public class MovieDocument
   {
       [BsonIgnoreIfDefault]
       public ObjectId Id { get; set; }
       public DateTime Released { get; set; }
       public string Title { get; set; }
       public double Score { get; set; }
   }

   ```

   Specify the `<connection-string>`.

2. Run the query.

   ```bash
   dotnet run Program.cs
   ```

   **Output:**

   ```json
   { "released" : ISODate("2015-01-28T00:00:00Z"), "title" : "Summer Nights", "score" : 0.348105788230896 }
   { "released" : ISODate("2014-08-01T00:00:00Z"), "title" : "Summertime", "score" : 0.59173756837844849 }
   { "released" : ISODate("2014-04-17T00:00:00Z"), "title" : "Summer of Blood", "score" : 0.99347203969955444 }
   { "released" : ISODate("2014-01-17T00:00:00Z"), "title" : "Summer in February", "score" : 0.62580311298370361 }
   { "released" : ISODate("2012-02-08T00:00:00Z"), "title" : "Summer Games", "score" : 0.15982933342456818 }
   ```

1) Define the query.

   Create a new file named `sort-by-date.js` and paste the following code:

   ```javascript
   const { MongoClient } = require("mongodb");

   // Replace the uri string with your MongoDB deployments connection string.
   const uri =
     "<connection-string>";

   const client = new MongoClient(uri);

   async function run() {
     try {
       await client.connect();

       // set namespace
       const database = client.db("sample_mflix");
       const coll = database.collection("movies");

       // define pipeline
       const agg = [
         {$search: {
           index: "default",
           compound: {
             filter: {wildcard: {query: "Summer*", path: "title"}},
             must: [{near: {path: "released", origin: new Date("2014-04-18T00:00:00.000Z"), pivot: 13149000000}}]
           },
           sort: { released: -1 }
         }},
       {$limit: 5},
       {$project: {_id: 0, title: 1, released: 1, score: {$meta: "searchScore"}}}
     ];
              
       // run pipeline
       const result = await coll.aggregate(agg);

       // print results
       await result.forEach((doc) => console.log(doc));
       
     } finally {
       await client.close();
     }
   }
   run().catch(console.dir);

   ```

   Specify the `<connection-string>`.

2) Run the query.

   ```bash
   node sort-by-date.js
   ```

   **Output:**

   ```json
   {
     title: 'Summer Nights',
     released: 2015-01-28T00:00:00.000Z,
     score: 0.348105788230896
   }
   {
     title: 'Summertime',
     released: 2014-08-01T00:00:00.000Z,
     score: 0.5917375683784485
   }
   {
     title: 'Summer of Blood',
     released: 2014-04-17T00:00:00.000Z,
     score: 0.9934720396995544
   }
   {
     title: 'Summer Games',
     released: 2012-02-08T00:00:00.000Z,
     score: 0.15982933342456818
   }
   {
     title: 'Summer of Goliath',
     released: 2011-07-08T00:00:00.000Z,
     score: 0.13038821518421173
   }
   ```

1. Define the query.

   Create a new file named `SortByDate.java` and paste the following code:

   ```java
   import java.util.Arrays;
   import java.util.List;

   import static com.mongodb.client.model.Aggregates.limit;
   import static com.mongodb.client.model.Aggregates.project;
   import static com.mongodb.client.model.Projections.*;
   import com.mongodb.client.MongoClient;
   import com.mongodb.client.MongoClients;
   import com.mongodb.client.MongoCollection;
   import com.mongodb.client.MongoDatabase;
   import org.bson.Document;

   import java.time.Instant;
   import java.util.Date;

   public class SortByDate {
     public static void main( String[] args ) {
       // define query
   	    Document agg =
   	        new Document("$search", 
   	        	    new Document("index", "default")
   	                .append("compound", 
   	        new Document("filter", Arrays.asList(new Document("wildcard", 
   	                        new Document("query", "Summer*")
   	                                .append("path", "title"))))
   	                    .append("must", Arrays.asList(new Document("near", 
   	                        new Document("pivot", 13149000000L)
   	                                .append("path", "released")
   	                                .append("origin", Date.from(Instant.parse("2014-04-18T00:00:00.000+00:00")))))))
   	                .append("sort", new Document("released", -1)));

       // specify connection
       String uri = "<connection-string>";

       // establish connection and set namespace
       try (MongoClient mongoClient = MongoClients.create(uri)) {
         MongoDatabase database = mongoClient.getDatabase("sample_mflix");
         MongoCollection<Document> collection = database.getCollection("movies");
   	  // run query and print results
         collection.aggregate(Arrays.asList(agg, 
           limit(5), 
           project(fields(exclude("_id"), include("title"), include("released"), computed("score", new Document("$meta", "searchScore"))))))
           .forEach(doc -> System.out.println(doc.toJson()));	
       }
     }
   }

   ```

   **Note:**

   To run the sample code in your Maven environment, add the following code above the import statements in your file.

   ```text
   package com.mongodb.drivers;
   ```

   Specify the `<connection-string>`.

2. Run the query.

   ```bash
   javac SortByDate.java
   java SortByDate
   ```

   **Output:**

   ```json
   {"title": "Summer Nights", "released": {"$date": "2015-01-28T00:00:00Z"}, "score": 0.348105788230896}
   {"title": "Summertime", "released": {"$date": "2014-08-01T00:00:00Z"}, "score": 0.5917375683784485}
   {"title": "Summer of Blood", "released": {"$date": "2014-04-17T00:00:00Z"}, "score": 0.9934720396995544}
   {"title": "Summer Games", "released": {"$date": "2012-02-08T00:00:00Z"}, "score": 0.15982933342456818}
   {"title": "Summer of Goliath", "released": {"$date": "2011-07-08T00:00:00Z"}, "score": 0.13038821518421173}
   ```

1) Define the query.

   Create a new file named `SortByDate.kt` and paste the following code:

   ```kotlin
   import com.mongodb.client.model.Aggregates.limit
   import com.mongodb.client.model.Aggregates.project
   import com.mongodb.client.model.Projections.*
   import com.mongodb.kotlin.client.coroutine.MongoClient
   import kotlinx.coroutines.runBlocking
   import org.bson.Document
   import java.time.Instant
   import java.util.*

   fun main() {
       // establish connection and set namespace
       val uri = "<connection-string>"
       val mongoClient = MongoClient.create(uri)
       val database = mongoClient.getDatabase("sample_mflix")
       val collection = database.getCollection<Document>("movies")

       runBlocking {
           // define query
           val agg = Document(
               "\$search",
               Document("index", "default")
                   .append(
                       "compound",
                       Document(
                           "filter", listOf(
                               Document(
                                   "wildcard",
                                   Document("query", "Summer*")
                                       .append("path", "title")
                               )
                           )
                       )
                           .append(
                               "must", listOf(
                                   Document(
                                       "near",
                                       Document("pivot", 13149000000L)
                                           .append("path", "released")
                                           .append("origin", Date.from(Instant.parse("2014-04-18T00:00:00.000+00:00")))
                                   )
                               )
                           )
                   )
                   .append("sort", Document("released", -1))
           )

           // run query and print results
           val resultsFlow = collection.aggregate<Document>(
               listOf(
                   agg,
                   limit(5),
                   project(fields(
                       excludeId(),
                       include("title", "released"),
                       computed("score", Document("\$meta", "searchScore"))
                   ))
               )
           )
           resultsFlow.collect { println(it) }
       }
       mongoClient.close()
   }

   ```

   Specify the `<connection-string>`.

2) Run the query.

   ```bash
   kotlin SortByDate.kt
   ```

   **Output:**

   ```json
   Document{{title=Summer Nights, released=Tue Jan 27 19:00:00 EST 2015, score=0.348105788230896}}
   Document{{title=Summertime, released=Thu Jul 31 20:00:00 EDT 2014, score=0.5917375683784485}}
   Document{{title=Summer of Blood, released=Wed Apr 16 20:00:00 EDT 2014, score=0.9934720396995544}}
   Document{{title=Summer Games, released=Tue Feb 07 19:00:00 EST 2012, score=0.15982933342456818}}
   Document{{title=Summer of Goliath, released=Thu Jul 07 20:00:00 EDT 2011, score=0.13038821518421173}}
   ```

1. Define the query.

   Create a new file named `sort-by-date.go` and paste the following code:

   ```go
   package main

   import (
   	"context"
   	"fmt"
   	"time"

   	"go.mongodb.org/mongo-driver/v2/bson"
   	"go.mongodb.org/mongo-driver/v2/mongo"
   	"go.mongodb.org/mongo-driver/v2/mongo/options"
   )

   func main() {
   	// connect to your Atlas cluster
   	client, err := mongo.Connect(options.Client().ApplyURI("<connection-string"))
   	if err != nil {
   		panic(err)
   	}
   	defer client.Disconnect(context.TODO())

   	// set namespace
   	collection := client.Database("sample_mflix").Collection("movies")

   	// define pipeline stages
   	searchStage := bson.D{{Key: "$search", Value: bson.M{
   		"index": "default",
   		"compound": bson.M{
   			"filter": bson.A{
   				bson.M{
   					"wildcard": bson.D{
   						{Key: "path", Value: "title"},
   						{Key: "query", Value: "Summer*"},
   					}},
   			},
   			"must": bson.A{
   				bson.M{
   					"near": bson.M{
   						"path":   "released",
   						"origin": time.Date(2014, time.April, 18, 0, 0, 0, 0, time.UTC),
   						"pivot":  13149000000}},
   			},
   		},
   		"sort": bson.D{{Key: "released", Value: -1}},
   	}}}

   	limitStage := bson.D{{Key: "$limit", Value: 5}}
   	projectStage := bson.D{{Key: "$project", Value: bson.D{{Key: "_id", Value: 0}, {Key: "title", Value: 1}, {Key: "released", Value: 1}, {Key: "score", Value: bson.D{{Key: "$meta", Value: "searchScore"}}}}}}

   	// run pipeline
   	cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
   	if err != nil {
   		panic(err)
   	}

   	// print results
   	var results []bson.D
   	if err = cursor.All(context.TODO(), &results); err != nil {
   		panic(err)
   	}
   	for _, result := range results {
   		fmt.Println(result)
   	}
   }

   ```

   Specify the `<connection-string>`.

2. Run the query.

   ```bash
   go run sort-by-date.go
   ```

   **Output:**

   ```json
   [{title Summer Nights} {released 1422403200000} {score 0.348105788230896}]
   [{title Summertime} {released 1406851200000} {score 0.5917375683784485}]
   [{title Summer of Blood} {released 1397692800000} {score 0.9934720396995544}]
   [{title Summer Games} {released 1328659200000} {score 0.15982933342456818}]
   [{title Summer of Goliath} {released 1310083200000} {score 0.13038821518421173}]
   ```

1) Define the query.

   Create a new file named `sort-by-date.py` and paste the following code:

   ```python
   import datetime
   import pymongo

   # connect to your Atlas cluster
   client = pymongo.MongoClient('<connection-string>')

   # define pipeline
   pipeline = [
     {'$search': {
         'index': 'default',
         'compound': {
           'filter': {'wildcard': {'query': 'Summer*', 'path': 'title'}},
           'must': {'near': {
             "path": "released", 
             "origin": datetime.datetime(2014, 4, 18, 0, 0, 0, 0), 
             "pivot": 13149000000
         }}},
         'sort': { 'released': -1 }}},
     {'$limit': 5},
     {'$project': {'_id': 0, 'title': 1, 'released': 1, 'score': {'$meta': 'searchScore'}}}
   ]

   # run pipeline
   result = client['sample_mflix']['movies'].aggregate(pipeline)

   # print results
   for i in result:
       print(i)

   ```

   Specify the `<connection-string>`.

2) Run the query.

   ```bash
   python sort-by-date.py
   ```

   **Output:**

   ```json
   {'title': 'Summer Nights', 'released': datetime.datetime(2015, 1, 28, 0, 0), 'score': 0.348105788230896}
   {'title': 'Summertime', 'released': datetime.datetime(2014, 8, 1, 0, 0), 'score': 0.5917375683784485}
   {'title': 'Summer of Blood', 'released': datetime.datetime(2014, 4, 17, 0, 0), 'score': 0.9934720396995544}
   {'title': 'Summer Games', 'released': datetime.datetime(2012, 2, 8, 0, 0), 'score': 0.15982933342456818}
   {'title': 'Summer of Goliath', 'released': datetime.datetime(2011, 7, 8, 0, 0), 'score': 0.13038821518421173}
   ```

### Number Search and Sort

The following query shows how to sort the results by a numeric field. It uses the [range](https://www.mongodb.com/docs/search/query/operators-collectors/range.md#std-label-range-ref) operator to search for movies that have won 10 or more awards and then sorts the results by the numeric field value in descending order.

The query uses the following pipeline stages:

- [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage to search the `awards.wins` field and sort the results in descending order.

- [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage to limit the output to `5` results.

- [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to exclude all fields except `title` and `awards.wins`.

1. Run the query.

   Copy and paste the following query into the Query Editor, and then click the Search button in the Query Editor.

   ```json
   [
     {
       "$search": {
         "range": {
           "path": "awards.wins",
           "gte": 10
         },
         "sort": {
           "awards.wins": -1,
         }
       }
     }
   ]
   ```

   **Output:**

   ```text
   SCORE: 1  _id:  "573a13d5f29313caabd9cae7"
     fullplot: "Based on an incredible true story of one man's fight for survival and …"
     imdb: Object
       ...
     year: 2013
     ...
     awards: Object
       wins: 267
       ...
     ...

   SCORE: 1  _id:  "573a13c7f29313caabd74a4d"
     fullplot: "Dr. Ryan Stone (Sandra Bullock) is a brilliant medical engineer on her…"
     imdb: Object
       ...
     year: 2013
     ...
     awards: Object
       wins: 231
       ...
     ...

   SCORE: 1  _id:  "573a13cbf29313caabd808d2"
     fullplot: "Dr. Ryan Stone (Sandra Bullock) is a brilliant medical engineer on her…"
     imdb: Object
       ...
     year: 2013
     ...
     awards: Object
       wins: 231
       ...
     ...

   SCORE: 1  _id:  “573a13dff29313caabdb7adb”"
     fullplot: "Actor Riggan Thomson is most famous for his movie role from over twent…"
     imdb: Object
       ...
     year: 2014
     ...
     awards: Object
       wins: 210
       ...
     ...

   SCORE: 1  _id:  "573a13bef29313caabd5c06c"
     plot: "The life of Mason, from early childhood to his arrival at college."
     imdb: Object
       ...
     runtime: 165
     ...
     awards: Object
       wins: 185
       ...
     ...

   SCORE: 1  _id:  "573a139ef29313caabcfbd6a"
     fullplot: "While Frodo & Sam continue to approach Mount Doom to destroy the One R…"
     imdb: Object
       ...
     year: 2003
     ...
     awards: Object
       wins: 175
       ...
     ...

   SCORE: 1  _id:  "573a13b5f29313caabd447f5"
     plot: "In rural Texas, welder and hunter Llewelyn Moss discovers the remains …"
     imdb: Object
       ...
     year: 2007
     ...
     awards: Object
       wins: 172
       ...
     ...

   SCORE: 1  _id:  "573a13c3f29313caabd68d9f"
     plot: "On a fall night in 2003, Harvard undergrad and computer programming ge…"
     imdb: Object
       ...
     year: 2010
     ...
     awards: Object
       wins: 171
       ...
     ...

   SCORE: 1  _id:  "573a13c5f29313caabd6ee61"
     fullplot: "Dom Cobb is a skilled thief, the absolute best in the dangerous art of…"
     imdb: Object
       ...
     year: 2010
     ...
     awards: Object
       wins: 162
       ...
     ...

   SCORE: 1  _id:  "573a13bdf29313caabd58fd3"
     plot: "The story of Jamal Malik, an 18 year-old orphan from the slums of Mumb…"
     imdb: Object
       ...
     year: 2008
     ...
     awards: Object
       wins: 161
       ...
     ...
   ```

2. Expand your query results.

   The Search Tester might not display all the fields in the documents it returns. To view all the fields, including the field that you specify in the query path, expand the document in the results.

To run the query in [`mongosh`:](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh)

```js
db.movies.aggregate([
  {
    "$search": {
      "range": {
        "path": "awards.wins",
        "gte": 10
      },
      "sort": {
        "awards.wins": -1,
      }
    }
  },
  {
    $limit: 5
  },
  {
    "$project": {
      "_id": 0,
      "title": 1,
      "awards.wins": 1
    }
  }
])
```

**Output:**

```json
[
  {
    title: '12 Years a Slave',
    awards: { wins: 267 }
  },
  {
    title: 'Gravity',
    awards: { wins: 231 }
  },
  {
    title: 'Gravity',
    awards: { wins: 231 }
  },
  {
    title: 'Birdman: Or (The Unexpected Virtue of Ignorance)',
    awards: { wins: 210 }
  },
  {
    title: 'Boyhood',
    awards: { wins: 185 }
  }
]
```

In MongoDB Compass, configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click Add Stage to add additional stages.

| Pipeline Stage | Query |
| --- | --- |
| `$search` | `{
  index: "default",
  "range": {
    "path": "awards.wins",
    "gte": 10
  },
  "sort": {
    "awards.wins": -1,
  }
}` |
| `$limit` | `5` |
| `$project` | `{
  title: 1,
  released: 1,
  year: 1
}` |

If you enabled Auto Preview, MongoDB Compass displays the following documents next to the `$limit` pipeline stage:

```javascript
[
  {
    title: '12 Years a Slave',
    awards: { wins: 267 }
  },
  {
    title: 'Gravity',
    awards: { wins: 231 }
  },
  {
    title: 'Gravity',
    awards: { wins: 231 }
  },
  {
    title: 'Birdman: Or (The Unexpected Virtue of Ignorance)',
    awards: { wins: 210 }
  },
  {
    title: 'Boyhood',
    awards: { wins: 185 }
  }
]
```

1. Define the query.

   In your project, replace the contents of the `Program.cs`  file with the following code.

   ```csharp
   using MongoDB.Bson;
   using MongoDB.Bson.Serialization.Attributes;
   using MongoDB.Bson.Serialization.Conventions;
   using MongoDB.Driver;
   using MongoDB.Driver.Search;

   public class SortByNumbers
   {
       private const string MongoConnectionString = "<connection-string>";

       public static void Main(string[] args)
       {
           // allow automapping of the camelCase database fields to our MovieDocument
           var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
           ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);

           // connect to your Atlas cluster
           var mongoClient = new MongoClient(MongoConnectionString);
           var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
           var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");

           // define search options
           var searchOptions = new SearchOptions<MovieDocument>() 
               { 
                   Sort = Builders<MovieDocument>.Sort.Descending(movies => movies.Awards.Wins),
                   IndexName = "default"
               };

           // define and run pipeline
           var results = moviesCollection.Aggregate()
               .Search(
                   Builders<MovieDocument>.Search.Range(movie => movie.Awards.Wins, SearchRangeBuilder.Gte(10)), searchOptions)
               .Project<MovieDocument>(Builders<MovieDocument>.Projection
                   .Exclude(movie => movie.Id)
                   .Include(movie => movie.Title)
                   .Include(movie => movie.Awards.Wins))
               .Limit(5)
               .ToList();

           // print results
           foreach (var movie in results)
           {
               Console.WriteLine(movie.ToJson());
           }
       }
   }

   [BsonIgnoreExtraElements]
   public class MovieDocument
   {
       [BsonIgnoreIfDefault]
       public ObjectId Id { get; set; }
       public string Title { get; set; }
       public Award Awards { get; set; }
   }

   public class Award
   {
       [BsonIgnoreIfDefault]
       public int Wins { get; set; }
   }

   ```

   Specify the `<connection-string>`.

2. Run the query.

   ```bash
   dotnet run Program.cs
   ```

   **Output:**

   ```json
   { "title" : "12 Years a Slave", "awards" : { "wins" : 267 } }
   { "title" : "Gravity", "awards" : { "wins" : 231 } }
   { "title" : "Gravity", "awards" : { "wins" : 231 } }
   { "title" : "Birdman: Or (The Unexpected Virtue of Ignorance)", "awards" : { "wins" : 210 } }
   { "title" : "Boyhood", "awards" : { "wins" : 185 } }
   ```

1) Define the query.

   Create a new file named `sort-by-numbers.js` and paste the following code:

   ```javascript
   const { MongoClient } = require("mongodb");

   // Replace the uri string with your MongoDB deployments connection string.
   const uri =
     "<connection-string>";

   const client = new MongoClient(uri);

   async function run() {
     try {
       await client.connect();

       // set namespace
       const database = client.db("sample_mflix");
       const coll = database.collection("movies");

       // define pipeline
       const agg = [
         {
           '$search': {
             'index': 'default',
             'range': {
               'path': 'awards.wins', 
               'gte': 10
             }, 
             'sort': {
               'awards.wins': -1
             }
           }
         }, {
           '$limit': 5
         }, {
           '$project': {
             '_id': 0, 
             'title': 1, 
             'awards.wins': 1
           }
         }
       ];

       // run pipeline
       const result = await coll.aggregate(agg);

       // print results
       await result.forEach((doc) => console.log(doc));

     } finally {
       await client.close();
     }
   }
   run().catch(console.dir);

   ```

   Specify the `<connection-string>`.

2) Run the query.

   ```bash
   node sort-by-numbers.js
   ```

   **Output:**

   ```json
   { title: '12 Years a Slave', awards: { wins: 267 } }
   { title: 'Gravity', awards: { wins: 231 } }
   { title: 'Gravity', awards: { wins: 231 } }
   {
     title: 'Birdman: Or (The Unexpected Virtue of Ignorance)',
     awards: { wins: 210 }
   }
   { title: 'Boyhood', awards: { wins: 185 } }
   ```

1. Define the query.

   Create a new file named `SortByNumbers.java` and paste the following code:

   ```java
   import java.util.Arrays;

   import static com.mongodb.client.model.Aggregates.limit;
   import static com.mongodb.client.model.Aggregates.project;
   import static com.mongodb.client.model.Projections.excludeId;
   import static com.mongodb.client.model.Projections.fields;
   import static com.mongodb.client.model.Projections.include;
   import com.mongodb.client.MongoClient;
   import com.mongodb.client.MongoClients;
   import com.mongodb.client.MongoCollection;
   import com.mongodb.client.MongoDatabase;
   import org.bson.Document;

   public class SortByNumbers {
     public static void main( String[] args ) {
       // define query
       Document agg =
           new Document("$search", 
           	    new Document("index", "default")
           	            .append("range", 
           	    new Document("path", "awards.wins")
           	                .append("gte", 10L))
           	            .append("sort", 
           	    new Document("awards.wins", -1L)));
       
       // specify connection
       String uri = "<connection-string>";
       
       // establish connection and set namespace
       try (MongoClient mongoClient = MongoClients.create(uri)) {
         MongoDatabase database = mongoClient.getDatabase("sample_mflix");
         MongoCollection<Document> collection = database.getCollection("movies");
   	  
         // run query and print results
         collection.aggregate(Arrays.asList(agg, 
           limit(5), 
           project(fields(excludeId(), include("title"), include("awards.wins")))))
           .forEach(doc -> System.out.println(doc.toJson()));	
       }
     }
   }

   ```

   **Note:**

   To run the sample code in your Maven environment, add the following code above the import statements in your file.

   ```text
   package com.mongodb.drivers;
   ```

   Specify the `<connection-string>`.

2. Run the query.

   ```bash
   javac SortByNumbers.java
   java SortByNumbers
   ```

   **Output:**

   ```json
   {"title": "12 Years a Slave", "awards": {"wins": 267}}
   {"title": "Gravity", "awards": {"wins": 231}}
   {"title": "Gravity", "awards": {"wins": 231}}
   {"title": "Birdman: Or (The Unexpected Virtue of Ignorance)", "awards": {"wins": 210}}
   {"title": "Boyhood", "awards": {"wins": 185}}
   ```

1) Define the query.

   Create a new file named `SortByNumbers.kt` and paste the following code:

   ```kotlin
   import com.mongodb.client.model.Aggregates.limit
   import com.mongodb.client.model.Aggregates.project
   import com.mongodb.client.model.Projections.*
   import com.mongodb.kotlin.client.coroutine.MongoClient
   import kotlinx.coroutines.runBlocking
   import org.bson.Document

   fun main() {
       // establish connection and set namespace
       val uri = "<connection-string>"
       val mongoClient = MongoClient.create(uri)
       val database = mongoClient.getDatabase("sample_mflix")
       val collection = database.getCollection<Document>("movies")

       runBlocking {
           // define query
           val agg = Document(
               "\$search",
               Document("index", "default")
                   .append(
                       "range",
                       Document("path", "awards.wins")
                           .append("gte", 10L)
                   )
                   .append(
                       "sort",
                       Document("awards.wins", -1L)
                   )
           )

           // run query and print results
           val resultsFlow = collection.aggregate<Document>(
               listOf(
                   agg,
                   limit(5),
                   project(fields(
                       excludeId(),
                       include("title", "awards.wins")
                   ))
               )
           )
           resultsFlow.collect { println(it) }
       }
       mongoClient.close()
   }

   ```

   Specify the `<connection-string>`.

2) Run the query.

   ```bash
   kotlin SortByNumbers.kt
   ```

   **Output:**

   ```json
   Document{{title=12 Years a Slave, awards=Document{{wins=267}}}}
   Document{{title=Gravity, awards=Document{{wins=231}}}}
   Document{{title=Gravity, awards=Document{{wins=231}}}}
   Document{{title=Birdman: Or (The Unexpected Virtue of Ignorance), awards=Document{{wins=210}}}}
   Document{{title=Boyhood, awards=Document{{wins=185}}}}
   ```

1. Define the query.

   Create a new file named `sort-by-numbers.go` and paste the following code:

   ```go
   package main

   import (
   	"context"
   	"fmt"

   	"go.mongodb.org/mongo-driver/v2/bson"
   	"go.mongodb.org/mongo-driver/v2/mongo"
   	"go.mongodb.org/mongo-driver/v2/mongo/options"
   )

   func main() {
   	// connect to your Atlas cluster
   	client, err := mongo.Connect(options.Client().ApplyURI("<connection-string>"))
   	if err != nil {
   		panic(err)
   	}
   	defer client.Disconnect(context.TODO())

   	// set namespace
   	collection := client.Database("sample_mflix").Collection("movies")

   	// define pipeline stages
   	searchStage := bson.D{{Key: "$search", Value: bson.D{
   		{Key: "index", Value: "default"},
   		{Key: "range", Value: bson.D{
   			{Key: "path", Value: "awards.wins"},
   			{Key: "gte", Value: 10},
   		}},
   		{Key: "sort", Value: bson.D{{Key: "awards.wins", Value: -1}}},
   	}}}
   	limitStage := bson.D{{Key: "$limit", Value: 5}}
   	projectStage := bson.D{{Key: "$project", Value: bson.D{{Key: "title", Value: 1}, {Key: "awards.wins", Value: 1}, {Key: "_id", Value: 0}}}}

   	// run pipeline
   	cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
   	if err != nil {
   		panic(err)
   	}

   	// print results
   	var results []bson.D
   	if err = cursor.All(context.TODO(), &results); err != nil {
   		panic(err)
   	}
   	for _, result := range results {
   		fmt.Println(result)
   	}
   }

   ```

   Specify the `<connection-string>`.

2. Run the query.

   ```bash
   go run sort-by-numbers.go
   ```

   **Output:**

   ```json
   [{title 12 Years a Slave} {awards [{wins 267}]}]
   [{title Gravity} {awards [{wins 231}]}]
   [{title Gravity} {awards [{wins 231}]}]
   [{title Birdman: Or (The Unexpected Virtue of Ignorance)} {awards [{wins 210}]}]
   [{title Boyhood} {awards [{wins 185}]}]
   ```

1) Define the query.

   Create a new file named `sort-by-numbers.py` and paste the following code:

   ```python
   import pymongo

   # connect to your Atlas cluster
   client = pymongo.MongoClient('<connection-string>')

   # define pipeline
   pipeline = [
     {
       '$search': {
         'index': 'default',
         'range': {
           'path': 'awards.wins',
           'gte': 10
         },
         'sort': {
           'awards.wins': -1
         }
       }
     }, {
       '$limit': 5
     }, {
       '$project': {'_id': 0, 'title': 1, 'awards.wins': 1
       }
     }
   ]

   # run pipeline
   result = client['sample_mflix']['movies'].aggregate(pipeline)

   # print results
   for i in result:
       print(i)

   ```

   Specify the `<connection-string>`.

2) Run the query.

   ```bash
   python sort-by-numbers.py
   ```

   **Output:**

   ```json
   {'title': '12 Years a Slave', 'awards': {'wins': 267}}
   {'title': 'Gravity', 'awards': {'wins': 231}}
   {'title': 'Gravity', 'awards': {'wins': 231}}
   {'title': 'Birdman: Or (The Unexpected Virtue of Ignorance)', 'awards': {'wins': 210}}
   {'title': 'Boyhood', 'awards': {'wins': 185}}
   ```

### String Search and Sort

#### Basic Example

The following query on the `sample_mflix.movies` namespace uses the [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage to do the following:

- Search for movies that have the term `country` in the title.

- Sort the results in ascending order using `sort` option.

The query uses the [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage to limit the output to `5` documents. It also uses the [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to do the following:

- Omit all fields except `title` in the results.

- Add a field named `score`.

```json
db.movies.aggregate([
  {
    "$search": {
      "text": {
        "path": "title",
        "query": "country"
      },
      "sort": {
        "title": 1
      }
    }
  },
  {
    "$limit": 5
  },
  {
    "$project": {
      "_id": 0,
      "title": 1,
      "score": { "$meta": "searchScore" }
    }
  }
])
```

**Output:**

```json
[
  { title: 'A Country Called Home', score: 2.536633253097534 },
  { title: 'A Month in the Country', score: 2.258953094482422 },
  { title: 'A Quiet Place in the Country', score: 2.0360684394836426 },
  { title: 'A Sunday in the Country', score: 2.258953094482422 },
  { title: 'Another Country', score: 3.3635599613189697 }
]
```

#### Compound Wildcard Search and Sort Example

The following query shows how to query and sort the results by a string field. It searches for titles that begin with `Prance` or `Prince` and sorts the results by the `title` field in ascending order.

The query uses the following pipeline stages:

- [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) to search the `title` field using the `should` clause with the [wildcard](https://www.mongodb.com/docs/search/query/operators-collectors/wildcard.md#std-label-wildcard-ref) operator to search for titles that begin with `Prance` and `Prince`. The query also specifies that results must be sorted by the `title` field in ascending order.

- [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage to limit the output to `5` results.

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

  - Exclude all fields except `title`.

  - Add a field named `score`.

```json
[
  {
    $search: {
      "compound": {
        "should": [{
          "wildcard": {
            "query": ["Prance*"],
            "path": "title",
            "allowAnalyzedField": true
          }
        },
        {
          "wildcard": {
            "query": ["Prince*"],
            "path": "title",
            "allowAnalyzedField": true
          }
        }]
      },
      "sort": {
        "title": 1
      }
    }
  }
]
```

**Output:**

```text
SCORE: 1  _id:  "573a1398f29313caabceb98e"
  plot: "A farm girl nurses a wounded reindeer she believes is one of Santa's, …"
  genres: Array
  runtime: 103
  ...
  title: "Prancer"
  ...

SCORE: 1  _id:  "573a13a5f29313caabd14f54"
  plot: "Preteen brothers from a broken marriage live with their mother, Denise…"
  genres: Array
  runtime: 91
  ...
  title: "Prancer Returns"
  ...

SCORE: 1  _id:  "573a13f5f29313caabde3755"
  plot: "A troubled teenager attempts to conquer the love of his life by becomi…"
  genres: Array
  runtime: 78
  ...
  title: "Prince"
  ...

SCORE: 1  _id:  "573a13d8f29313caabda665f"
  fullplot: "Two highway road workers spend the summer of 1988 away from their city…"
  imdb: Object
  year: 2013
  ...
  title: "Prince Avalanche"
  ...

SCORE: 1  _id:  "573a13bdf29313caabd5898a"
  plot: "A New York street drama about the lives of immigrants in America seeki…"
  genres: Array
  runtime: 70
  ...
  title: "Prince of Broadway"
  ...

SCORE: 1  _id:  "573a1398f29313caabcea967"
  fullplot: "A sinister secret has been kept in the basement of an abandoned Los An…"
  imdb: Object
  year: 1987
  ...
  title: "Prince of Darkness"
  ...

SCORE: 1  _id:  "573a1393f29313caabcde40d"
  plot: "An unscrupulous agent for the Borgias suffers a change of heart when a…"
  genres: Array
  runtime: 107
  ...
  title: "Princess of Foxes"
  ...

SCORE: 1  _id:  "573a13b5f29313caabd43816"
  plot: "A young fugitive prince and princess must stop a villain who unknowing…"
  genres: Array
  runtime: 116
  ...
  title: "Prince of Persia: The Sands of Time"
  ...

SCORE: 1  _id:  "573a1397f29313caabce8081"
  plot: "A New York City narcotics detective reluctantly agrees to cooperate wi…"
  genres: Array
  runtime: 167
  ...
  title: "Prince of the City"
  ...

SCORE: 1  _id:  "573a13a2f29313caabd0a767"
  plot: "Six old-style funny silhouetted fairy tales for not so-old-style peopl…"
  genres: Array
  runtime: 70
  ...
  title: "Princes and Princesses"
  ...
```

The MongoDB Search results contain documents with movie titles that begin with `Prance` and `Prince`. MongoDB Search returns titles with `Prance` followed by `Prince` because MongoDB Search sorts documents by the `title` field in ascending order.

The Search Tester might not display all the fields in the documents it returns. To view all the fields, including the field that you specify in the query path, expand the document in the results.

```js
db.movies.aggregate([{ 
  $search: { 
    "index": "default",
    "compound": {
      "should": [{
        "wildcard": {
          "query": ["Prance*"],
          "path": "title",
          "allowAnalyzedField": true
        }
      },
      {
        "wildcard": {
          "query": ["Prince*"],
          "path": "title",
          "allowAnalyzedField": true
        }
      }]
    },
    "sort": {
      "title": 1
    }
  }},
  { 
    $limit: 5
  },
  {
    $project: {
      "_id": 0,
      "title": 1,
      "score": { "$meta": "searchScore" }
    }
  }
])

```

**Output:**

```shell
[
  { title: 'Prancer', score: 1 },
  { title: 'Prancer Returns', score: 1 },
  { title: 'Prince', score: 1 },
  { title: 'Prince Avalanche', score: 1 },
  { title: 'Prince of Broadway', score: 1 }
]
```

The MongoDB Search results contain documents with movie titles that begin with `Prance` and `Prince`. MongoDB Search returns titles with `Prance` followed by `Prince` because MongoDB Search sorts documents by the `title` field in ascending order.

| Pipeline Stage | Query |
| --- | --- |
| `$search` | `{
  compound: {
    should: [{
      wildcard: {
      query: "Prance*",
      path: 'title',
      allowAnalyzedField: true
      }},
    {
      wildcard: {
      query: "Prince*",
      path: 'title',
      allowAnalyzedField: true
      }
    }]
  },
  sort: {
    title: 1
  }
}` |
| `$limit` | `5` |
| `$project` | `{
  _id: 0,
  title: 1,
  score: { $meta: "searchScore" }
}` |

If you enabled Auto Preview, MongoDB Compass displays the following documents next to the `$project` pipeline stage:

```javascript
{
 title: 'Prancer',
 score: 1
},
{
 title: 'Prancer Returns',
 score: 1
},
{
 title: 'Prince',
 score: 1
},
{
 title: 'Prince Avalanche',
 score: 1
},
{
 title: 'Prince of Boradway',
 score: 1
}
```

The MongoDB Search results contain documents with movie titles that begin with `Prance` and `Prince`. MongoDB Search returns titles with `Prance` followed by `Prince` because MongoDB Search sorts documents by the `title` field in ascending order.

The code example performs the following tasks:

- Imports `mongodb` packages and dependencies.

- Establishes a connection to your cluster.

- The query uses the following pipeline stages:
  - [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) to search the `title` field using the `should` clause with the [wildcard](https://www.mongodb.com/docs/search/query/operators-collectors/wildcard.md#std-label-wildcard-ref) operator to search for titles that begin with `Prance` and `Prince`. The query also specifies that results must be sorted by the `title` field in ascending order.

  - [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage to limit the output to `5` results.

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

    - Exclude all fields except `title`.

    - Add a field named `score`.

- Iterates over the cursor to print the documents that match the query.

```csharp
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using MongoDB.Driver.Search;

public class SortByStrings
{
    private const string MongoConnectionString = "<connection-string>";

    public static void Main(string[] args)
    {
        // allow automapping of the camelCase database fields to our MovieDocument
        var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
        ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);

        // connect to your Atlas cluster
        var mongoClient = new MongoClient(MongoConnectionString);
        var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
        var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");

        // define search options
        var searchOptions = new SearchOptions<MovieDocument>() 
            { 
                Sort = Builders<MovieDocument>.Sort.Ascending(movie => movie.Title),
                IndexName = "default"
            };

        // define and run pipeline
        var results = moviesCollection.Aggregate()
            .Search(Builders<MovieDocument>.Search.Compound()
                .Should(Builders<MovieDocument>.Search.Wildcard(movie => movie.Title, "Prance*", true ))
                .Should(Builders<MovieDocument>.Search.Wildcard(movie => movie.Title, "Prince*" )), searchOptions)
            .Project<MovieDocument>(Builders<MovieDocument>.Projection
                .Include(movie => movie.Title)
                .Exclude(movie => movie.Id)
                .MetaSearchScore(movie => movie.Score))
            .Limit(5)
            .ToList();

        // print results
        foreach (var movie in results)
        {
            Console.WriteLine(movie.ToJson());
        }
    }
}

[BsonIgnoreExtraElements]
public class MovieDocument
{
    [BsonIgnoreIfDefault]
    public ObjectId Id { get; set; }
    public string Title { get; set; }
    public double Score { get; set; }
}

```

**Output:**

```json
{ "title" : "Prancer", "score" : 1.0 }
{ "title" : "Prancer Returns", "score" : 1.0 }
{ "title" : "Prince", "score" : 1.0 }
{ "title" : "Prince Avalanche", "score" : 1.0 }
{ "title" : "Prince of Broadway", "score" : 1.0 }
```

The MongoDB Search results contain documents with movie titles that begin with `Prance` and `Prince`. MongoDB Search returns titles with `Prance` followed by `Prince` because MongoDB Search sorts documents by the `title` field in ascending order.

The code example performs the following tasks:

- Imports `mongodb`, MongoDB's Node.js driver.

- Creates an instance of the `MongoClient` class to establish a connection to your cluster.

- The query uses the following pipeline stages:
  - [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) to search the `title` field using the `should` clause with the [wildcard](https://www.mongodb.com/docs/search/query/operators-collectors/wildcard.md#std-label-wildcard-ref) operator to search for titles that begin with `Prance` and `Prince`. The query also specifies that results must be sorted by the `title` field in ascending order.

  - [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage to limit the output to `5` results.

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

    - Exclude all fields except `title`.

    - Add a field named `score`.

- Iterates over the cursor to print the documents that match the query.

```javascript
const { MongoClient } = require("mongodb");

// Replace the uri string with your MongoDB deployments connection string.
const uri =
  "<connection-string>";

const client = new MongoClient(uri);

async function run() {
  try {
    await client.connect();

    // set namespace
    const database = client.db("sample_mflix");
    const coll = database.collection("movies");

    // define pipeline
    const agg = [
      {
        '$search': {
          'compound': {
            'should': [
              {
                'wildcard': {
                  'query': [
                    'Prance*'
                  ], 
                  'path': 'title', 
                  'allowAnalyzedField': true
                }
              }, {
                'wildcard': {
                  'query': [
                    'Prince*'
                  ], 
                  'path': 'title', 
                  'allowAnalyzedField': true
                }
              }
            ]
          }, 
          'sort': { 'title': 1 }
        }
      }, {
        '$limit': 5
      }, {
        '$project': {'_id': 0, 'title': 1, 'score': {'$meta': 'searchScore'}
        }
      }
    ];
           
    // run pipeline
    const result = await coll.aggregate(agg);

    // print results
    await result.forEach((doc) => console.log(doc));
    
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

```

**Output:**

```javascript
{ title: 'Prancer', score: 1 }
{ title: 'Prancer Returns', score: 1 }
{ title: 'Prince', score: 1 }
{ title: 'Prince Avalanche', score: 1 }
{ title: 'Prince of Broadway', score: 1 }
```

The MongoDB Search results contain documents with movie titles that begin with `Prance` and `Prince`. MongoDB Search returns titles with `Prance` followed by `Prince` because MongoDB Search sorts documents by the `title` field in ascending order.

The code example performs the following tasks:

- Imports `mongodb` packages and dependencies.

- Establishes a connection to your cluster.

- Iterates over the cursor to print the documents that match the query.

```java
import java.util.Arrays;
import java.util.List;

import static com.mongodb.client.model.Aggregates.limit;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Projections.*;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.util.Date;

public class SortByString {
  public static void main( String[] args ) {
    // define clause
    List<Document> shouldClause =
        List.of(
            new Document(
                "wildcard",
                new Document("query", "Prance*")
                    .append("path", "title")
                    .append("allowAnalyzedField", true)),
            new Document(
                "wildcard",
                new Document("query", "Prince*")
                    .append("path", "title")
                    .append("allowAnalyzedField", true)));
    
    // define query
    Document agg =
        new Document(
            "$search",
            new Document("index", "default")
            .append("compound",
                new Document("should", shouldClause))
                .append("sort", new Document("title", 1L)));
    
    // specify connection
    String uri = "<connection-string>";
    
    // establish connection and set namespace
    try (MongoClient mongoClient = MongoClients.create(uri)) {
      MongoDatabase database = mongoClient.getDatabase("sample_mflix");
      MongoCollection<Document> collection = database.getCollection("movies");
	  
      // run query and print results
      collection.aggregate(Arrays.asList(agg, 
        limit(5),
        project(fields(excludeId(), include("title"), computed("score", new Document("$meta", "searchScore"))))))
        .forEach(doc -> System.out.println(doc.toJson()));	
    }
  }
}

```

**Output:**

```json
{"title": "Prancer", "score": 1.0}
{"title": "Prancer Returns", "score": 1.0}
{"title": "Prince", "score": 1.0}
{"title": "Prince Avalanche", "score": 1.0}
{"title": "Prince of Broadway", "score": 1.0}
```

The MongoDB Search results contain documents with movie titles that begin with `Prance` and `Prince`. MongoDB Search returns titles with `Prance` followed by `Prince` because MongoDB Search sorts documents by the `title` field in ascending order.

The code example performs the following tasks:

- Imports `mongodb` packages and dependencies.

- Establishes a connection to your cluster.

- Prints the documents that match the query from the `AggregateFlow` instance.

```kotlin
import com.mongodb.client.model.Aggregates.limit
import com.mongodb.client.model.Aggregates.project
import com.mongodb.client.model.Projections.*
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import org.bson.Document

fun main() {
    // establish connection and set namespace
    val uri = "<connection-string>"
    val mongoClient = MongoClient.create(uri)
    val database = mongoClient.getDatabase("sample_mflix")
    val collection = database.getCollection<Document>("movies")

    runBlocking {
        // define clause
        val shouldClause = listOf(
            Document("wildcard", Document("query", "Prance*")
                .append("path", "title")
                .append("allowAnalyzedField", true)),
            Document("wildcard", Document("query", "Prince*")
                .append("path", "title")
                .append("allowAnalyzedField", true))
        )

        // define query
        val agg = Document(
            "\$search",
            Document("index", "default")
                .append(
                    "compound",
                    Document("should", shouldClause)
                )
                .append("sort", Document("title", 1L))
        )

        // run query and print results
        val resultsFlow = collection.aggregate<Document>(
            listOf(
                agg,
                limit(5),
                project(fields(
                    excludeId(),
                    include("title"),
                    computed("score", Document("\$meta", "searchScore"))
                ))
            )
        )
        resultsFlow.collect { println(it) }
    }
    mongoClient.close()
}

```

**Output:**

```shell
Document{{title=Prancer, score=1.0}}
Document{{title=Prancer Returns, score=1.0}}
Document{{title=Prince, score=1.0}}
Document{{title=Prince Avalanche, score=1.0}}
Document{{title=Prince of Broadway, score=1.0}}
```

The MongoDB Search results contain documents with movie titles that begin with `Prance` and `Prince`. MongoDB Search returns titles with `Prance` followed by `Prince` because MongoDB Search sorts documents by the `title` field in ascending order.

The code example performs the following tasks:

- Imports `mongodb` packages and dependencies.

- Establishes a connection to your cluster.

- Iterates over the cursor to print the documents that match the query.

```go
package main

import (
	"context"
	"fmt"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
	// connect to your Atlas cluster
	client, err := mongo.Connect(options.Client().ApplyURI("<connection-string>"))
	if err != nil {
		panic(err)
	}
	defer client.Disconnect(context.TODO())

	// set namespace
	collection := client.Database("sample_mflix").Collection("movies")

	// define pipeline stages
	searchStage := bson.D{{Key: "$search", Value: bson.M{
		"index": "default",
		"compound": bson.M{
			"should": bson.A{
				bson.M{
					"wildcard": bson.D{
						{Key: "path", Value: "title"},
						{Key: "query", Value: "Prance*"},
						{Key: "allowAnalyzedField", Value: true},
					}},
				bson.M{
					"wildcard": bson.D{
						{Key: "path", Value: "title"},
						{Key: "query", Value: "Prince*"},
						{Key: "allowAnalyzedField", Value: true},
					}},
			},
		},
		"sort": bson.D{{Key: "title", Value: 1}},
	}}}

	limitStage := bson.D{{Key: "$limit", Value: 5}}
	projectStage := bson.D{{Key: "$project", Value: bson.D{{Key: "title", Value: 1}, {Key: "_id", Value: 0}, {Key: "score", Value: bson.D{{Key: "$meta", Value: "searchScore"}}}}}}

	// run pipeline
	cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
	if err != nil {
		panic(err)
	}

	// print results
	var results []bson.D
	if err = cursor.All(context.TODO(), &results); err != nil {
		panic(err)
	}
	for _, result := range results {
		fmt.Println(result)
	}
}

```

**Output:**

```none
[{title Prancer} {score 1}]
[{title Prancer Returns} {score 1}]
[{title Prince} {score 1}]
[{title Prince Avalanche} {score 1}]
[{title Prince of Broadway} {score 1}]
```

The MongoDB Search results contain documents with movie titles that begin with `Prance` and `Prince`. MongoDB Search returns titles with `Prance` followed by `Prince` because MongoDB Search sorts documents by the `title` field in ascending order.

The following code example:

- Imports `pymongo`, MongoDB's Python driver, and the `dns` module, which is required to connect `pymongo` to `Atlas` using a DNS (Domain Name System) seed list connection string.

- Creates an instance of the `MongoClient` class to establish a connection to your cluster.

- The query uses the following pipeline stages:
  - [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) to search the `title` field using the `should` clause with the [wildcard](https://www.mongodb.com/docs/search/query/operators-collectors/wildcard.md#std-label-wildcard-ref) operator to search for titles that begin with `Prance` and `Prince`. The query also specifies that results must be sorted by the `title` field in ascending order.

  - [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage to limit the output to `5` results.

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

    - Exclude all fields except `title`.

    - Add a field named `score`.

- Iterates over the cursor to print the documents that match the query.

```python
import pymongo

# connect to your Atlas cluster
client = pymongo.MongoClient('<connection-string>')

# define pipeline
pipeline = [
  {'$search': {
      'compound': {
        'should': [{'wildcard': {'query': 'Prance*', 'path': 'title', 'allowAnalyzedField': True}},
                   {'wildcard': {'query': 'Prince*', 'path': 'title', 'allowAnalyzedField': True}}]
      }, 
      'sort': { 'title': 1 }}},
  {'$limit': 5},
  {'$project': {'_id': 0, 'title': 1, 'score': {'$meta': 'searchScore'}}}
]

# run pipeline
result = client['sample_mflix']['movies'].aggregate(pipeline)

# print results
for i in result:
    print(i)

```

**Output:**

```python
{'title': 'Prancer', 'score': 1.0}
{'title': 'Prancer Returns', 'score': 1.0}
{'title': 'Prince', 'score': 1.0}
{'title': 'Prince Avalanche', 'score': 1.0}
{'title': 'Prince of Broadway', 'score': 1.0}
```

The MongoDB Search results contain documents with movie titles that begin with `Prance` and `Prince`. MongoDB Search returns titles with `Prance` followed by `Prince` because MongoDB Search sorts documents by the `title` field in ascending order.

#### Cases-Insensitive Sort Example

The following query shows how to sort the results regardless of the letter case. It uses the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref) operator to search for movies that have the term `train` in the `title` field and then sorts the results by the `title` field value in ascending order.

The query specifies a [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage to limit the documents in the results to `5` and a [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to do the following:

- Include only the `_id`, `title`, and `awards` fields in the results.

- Add a field named [score](https://www.mongodb.com/docs/search/query/score/overview.md#std-label-scoring-ref) in the results.

```json
[
  {
    "$search": {
      "text": {
        "path": "title",
        "query": "train",
      },
      "sort": {
        "title": 1
      }
    }
  }
]
```

**Output:**

```shell
SCORE: 3.317898988723755  _id: "573a139cf29313caabcf662c"
plot: "A train filled with atomic devices threatens to destroy the city of De…"
genres: Array
runtime: 122

SCORE: 3.317898988723755  _id: "64de50ae2932de4dd3203061"
genres: Array
title: "atomic train"
awards: Object

SCORE: 2.228306293487549  _id: "573a13bbf29313caabd52ff4"
fullplot: "Long ago up North on the Island of Berk, the young Viking, Hiccup, wan…"
imdb: Object
year: 2010

SCORE: 2.228306293487549  _id: "64de50da2932de4dd3204393"
genres: Array
title: "how to train your dragon"
awards: Object

SCORE: 2.008449077606201  _id: "573a13ccf29313caabd83281"
plot: "When Hiccup and Toothless discover an ice cave that is home to hundred…"
genres: Array
runtime: 102

SCORE: 1.4400973320007324  _id: "573a13b1f29313caabd36490"
plot: "The life and times of Howard Zinn: the historian, activist, and author…"
genres: Array
runtime: 78

SCORE: 2.228306293487549  _id: "573a1394f29313caabce0fb4"
plot: "A marshal tries to bring the son of an old friend, an autocratic cattl…"
genres: Array
runtime: 95

SCORE: 2.8528976440429688  _id: "573a13c8f29313caabd78a6b"
plot: "A couple embarks on a journey home for Chinese new year along with 130…"
genres: Array
runtime: 85

SCORE: 2.502213716506958  _id: "573a13baf29313caabd50811"
plot: "Two thugs from the Perth suburb of Midland catch the last train to Fre…"
genres: Array
runtime: 89

SCORE: 2.502213716506958  _id: "573a13a7f29313caabd1b667"
fullplot: "A teacher and a gangster meet by chance in a small town pharmacy. As a…"
imdb: Object
year: 2002
```

The results contain documents sorted regardless of the letter case. However, if you set `normalizer` to `none`, MongoDB Search returns the following results:

```json
SCORE: 3.317898988723755  _id: "573a139cf29313caabcf662c"
plot: "A train filled with atomic devices threatens to destroy the city of De…"
genres: Array
runtime: 122

SCORE: 2.2382168769836426  _id: "573a13bbf29313caabd52ff4"
fullplot: "Long ago up North on the Island of Berk, the young Viking, Hiccup, wan…"
imdb: object
year: 2010

SCORE: 2.008449077606201  _id: "573a13ccf29313caabd83281"
plot: "When Hiccup and Toothless discover an ice cave that is home to hundred…"
genres: Array
runtime: 102

SCORE: 1.4400973320007324  _id: "573a13b1f29313caabd36490"
plot: "The life and times of Howard Zinn: the historian, activist, and author…"
genres: Array
runtime: 78

SCORE: 2.8528976440429688  _id: "573a13c8f29313caabd78a6b"
plot: "A couple embarks on a journey home for Chinese new year along with 130…"
genres: Array
runtime: 85

SCORE: 2.228306293487549  _id: "573a1394f29313caabce0fb4"
plot: "A marshal tries to bring the son of an old friend, an autocratic cattl…"
genres: Array
runtime: 95

SCORE: 2.502213716506958  _id: "573a13baf29313caabd50811"
plot: "Two thugs from the Perth suburb of Midland catch the last train to Fre…"
genres: Array
runtime: 89

SCORE: 2.502213716506958  _id: "573a13a7f29313caabd1b667"
fullplot: "A teacher and a gangster meet by chance in a small town pharmacy. As a…"
imdb: Object
year: 2002

SCORE: 3.3326687812805176  _id: "573a139af29313caabcef573"
plot: "A vengeful New York transit cop decides to steal a trainload of subway…"
genres: Array
runtime: 110

SCORE: 3.3326687812805176  _id: "573a1398f29313caabceb8f2"
plot: "Three stories are connected by a Memphis hotel and the spirit of Elvis…"
genres: Array
runtime: 110
```

To sort your results without normalizing the letter case, set the `normalizer` option to `none` (on line 7) in your index definition, save the index definition, and rerun the query.

```json
db.movies.aggregate(
  {
    "$search": {
      "index": "default",
      "text": {
        "path": "title",
        "query": "train",
      },
      "sort": {
        "title": 1
      }
    }
  },
  {
    "$limit": 5
  },
  {
    "$project": {
      "_id": 1,
      "title": 1,
      "awards": 1,
      "score": { $meta: "searchScore" }
    }
  }
)
```

**Output:**

```javascript
[
  {
    _id: ObjectId("573a139cf29313caabcf662c"),
    title: 'Atomic Train',
    awards: { wins: 1, nominations: 1, text: '1 win & 1 nomination.' },
    score: 3.317898988723755
  },
  {
    _id: ObjectId("64de50ae2932de4dd3203061"),
    title: 'atomic train',
    awards: { wins: 1, nominations: 1 },
    score: 3.317898988723755
  },
  {
    _id: ObjectId("573a13bbf29313caabd52ff4"),
    title: 'How to Train Your Dragon',
    awards: {
      wins: 32,
      nominations: 51,
      text: 'Nominated for 2 Oscars. Another 30 wins & 51 nominations.'
    },
    score: 2.228306293487549
  },
  {
    _id: ObjectId("64de50da2932de4dd3204393"),
    title: 'how to train your dragon',
    awards: { wins: 32, nominations: 51 },
    score: 2.228306293487549
  },
  {
    _id: ObjectId("573a13ccf29313caabd83281"),
    title: 'How to Train Your Dragon 2',
    awards: {
      wins: 18,
      nominations: 52,
      text: 'Nominated for 1 Oscar. Another 17 wins & 52 nominations.'
    },
    score: 2.008449077606201
  }
]
```

The results contain documents sorted regardless of the letter case. However, if you set `normalizer` to `none`, MongoDB Search returns the following results:

```json
[
  {
    _id: ObjectId("573a139cf29313caabcf662c"),
    title: 'Atomic Train',
    awards: { wins: 1, nominations: 1, text: '1 win & 1 nomination.' },
    score: 3.3326687812805176
  },
 {
    _id: ObjectId("573a13bbf29313caabd52ff4"),
    title: 'How to Train Your Dragon',
    awards: {
      wins: 32,
      nominations: 51,
      text: 'Nominated for 2 Oscars. Another 30 wins & 51 nominations.'
    },
    score: 2.2382168769836426
  },
  {
    _id: ObjectId("573a13ccf29313caabd83281"),
    title: 'How to Train Your Dragon 2',
    awards: {
      wins: 18,
     nominations: 52,
      text: 'Nominated for 1 Oscar. Another 17 wins & 52 nominations.'
    },
    score: 2.0173802375793457
  },
  {
    _id: ObjectId("573a13b1f29313caabd36490"),
    title: "Howard Zinn: You Can't Be Neutral on a Moving Train",
    awards: { wins: 1, nominations: 0, text: '1 win.' },
    score: 1.446497917175293
  },
  {
    _id: ObjectId("573a13c8f29313caabd78a6b"),
    title: 'Last Train Home',
    awards: { wins: 14, nominations: 9, text: '14 wins & 9 nominations.' },
    score: 2.8655927181243896
  }
]
```

To sort your results without normalizing the letter case, set the `normalizer` option to `none` (on line 7) in your index definition, save the index definition, and rerun the query.

| Pipeline Stage | Query |
| --- | --- |
| `$search` | `{
  "index": "default",
  "text": {
    "path": "title",
    "query": "train",
  },
  "sort": {
    "title": 1,
  }
}` |
| `$limit` | `5` |
| `$project` | `{
  "_id": 1,
  "title": 1,
  "awards": 1,
  "score": { $meta: "searchScore" }
}` |

If you [enabled](https://www.mongodb.com/docs/compass/current/aggregation-pipeline-builder/#set-the-documents-limit-or-auto-preview-documents) Auto Preview, MongoDB Compass displays the following documents next to the `$project` pipeline stage:

```json
_id: ObjectId('573a139cf29313caabcf662c')
title: 'Atomic Train'
awards: Object
score: 3.317898988723755

_id:  ObjectId("64de50ae2932de4dd3203061")
title: 'atomic train'
awards: Object
score: 3.317898988723755

_id: ObjectId('573a13bbf29313caabd52ff4')
title: 'How to Train Your Dragon'
awards: Object
score: 2.228306293487549

_id: ObjectId("64de50da2932de4dd3204393"),
title: 'how to train your dragon'
awards:
score: 2.228306293487549

_id: ObjectId('573a13ccf29313caabd83281')
title: 'How to Train Your Dragon 2'
awards: object
score: 2.0173802375793457
```

The results contain documents sorted regardless of the letter case. However, if you set `normalizer` to `none`, MongoDB Search returns the following results:

```csharp
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using MongoDB.Driver.Search;

public class CaseInsensitiveSort
{
    private const string MongoConnectionString = "<connection-string>";

    public static void Main(string[] args)
    {
        // allow automapping of the camelCase database fields to our MovieDocument
        var camelCaseConvention = new ConventionPack { new camelCaseConvention() };
        ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);

        // connect to your Atlas cluster
        var mongoClient = new MongoClient(MongoConnectionString);
        var yourDatabase = mongoClient.GetDatabase("sample_mflix");
        var moviesCollection = yourDatabase.GetCollection<MovieDocument>("movies");
        
        // define options for search 
        var searchOptions = new SearchOptions<MovieDocument>() {
            Sort = Builders<MovieDocument>.Sort.Ascending(movie => movie.Title), 
            IndexName = "default"
        };
        
        // define and run pipeline
        var results = moviesCollection.Aggregate()
            .Search(Builders<MovieDocument>.Search.Text(movie => movie.Title, "train"), searchOptions)
            .Limit (5)
            .Project<MovieDocument>(Builders<MovieDocument>.Projection
                .Include(movie => movie.Id)
                .Include(movie => movie.Title)
                .Include(movie => movie.Awards)
                .MetaSearchScore(movie => movie.Score))
            .ToList();

        // print results
        foreach (var movie in results)
        {
            Console.WriteLine(movie.ToJson());
        }
    }
}

[BsonIgnoreExtraElements]
public class MovieDocument
{
    [BsonIgnoreIfDefault]
    public ObjectId Id { get; set; }
    public string Title { get; set; }
    public Award Awards { get; set; }
    public double Score { get; set; }
}

[BsonIgnoreExtraElements]
public class Award
{
    public int Wins { get; set; }
    public int Nominations { get; set; }
}

```

**Output:**

```javascript
{ "_id" : ObjectId("573a139cf29313caabcf662c"), "title" : "Atomic Train", "awards" : { "wins" : 1, "nominations" : 1 }, "score" : 3.3035578727722168 }
{ "_id" : ObjectId("64de50ae2932de4dd3203061"), "title" : "atomic train", "awards" : { "wins" : 1, "nominations" : 1 }, "score" : 3.3035578727722168 }
{ "_id" : ObjectId("573a13bbf29313caabd52ff4"), "title" : "How to Train Your Dragon", "awards" : { "wins" : 32, "nominations" : 51 }, "score" : 2.2186923027038574 }
{ "_id" : ObjectId("64de50da2932de4dd3204393"), "title" : "how to train your dragon", "awards" : { "wins" : 32, "nominations" : 51 }, "score" : 2.2186923027038574 }
{ "_id" : ObjectId("573a13ccf29313caabd83281"), "title" : "How to Train Your Dragon 2", "awards" : { "wins" : 18, "nominations" : 52 }, "score" : 1.9997868537902832 }
```

The results contain documents sorted regardless of the letter case. However, if you set `normalizer` to `none`, MongoDB Search returns the following results:

```shell
{ "_id" : ObjectId("573a139cf29313caabcf662c"), "title" : "Atomic Train", "awards" : { "wins" : 1, "nominations" : 1 }, "score" : 3.3035225868225098 }
{ "_id" : ObjectId("573a13bbf29313caabd52ff4"), "title" : "How to Train Your Dragon", "awards" : { "wins" : 32, "nominations" : 51 }, "score" : 2.2186522483825684 }
{ "_id" : ObjectId("573a13ccf29313caabd83281"), "title" : "How to Train Your Dragon 2", "awards" : { "wins" : 18, "nominations" : 52 }, "score" : 1.9997482299804688 }
{ "_id" : ObjectId("573a13b1f29313caabd36490"), "title" : "Howard Zinn: You Can't Be Neutral on a Moving Train", "awards" : { "wins" : 1, "nominations" : 0 }, "score" : 1.4338588714599609 }
{ "_id" : ObjectId("573a13c8f29313caabd78a6b"), "title" : "Last Train Home", "awards" : { "wins" : 14, "nominations" : 9 }, "score" : 2.8405368328094482 }
```

To sort your results without normalizing the letter case, set the `normalizer` option to `none` (on line 7) in your index definition, save the index definition, and rerun the query.

```go
package main

import (
	"context"
	"fmt"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	// connect to your Atlas cluster
	client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
	if err != nil {
		panic(err)
	}
	defer client.Disconnect(context.TODO())

	// set namespace
	collection := client.Database("sample_mflix").Collection("movies")

	// define pipeline stages
	searchStage := bson.D{{"$search", bson.M{
		"index": "default",
		"text": bson.D{
			{"path", "title"},
			{"query", "train"},
		},
		"sort": bson.D{{"title", 1}},
	}}}
	limitStage := bson.D{{"$limit", 5}}
	projectStage := bson.D{{"$project", bson.D{{"_id", 1}, {"title", 1}, {"awards", 1}, {"score", bson.D{{"$meta", "searchScore"}}}}}}

	// run pipeline
	cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
	if err != nil {
		panic(err)
	}

	// print results
	var results []bson.D
	if err = cursor.All(context.TODO(), &results); err != nil {
		panic(err)
	}
	for _, result := range results {
		fmt.Println(result)
	}
}

```

**Output:**

```javascript
[{_id ObjectID("573a139cf29313caabcf662c")} {title Atomic Train} {awards [{wins 1} {nominations 1} {text 1 win & 1 nomination.}]} {score 3.317898988723755}]
[{_id ObjectId("64de50ae2932de4dd3203061")} {title atomic train} {awards [{wins 1} {nominations 1}]} {score 3.317898988723755}]
[{_id ObjectID("573a13bbf29313caabd52ff4")} {title How to Train Your Dragon} {awards [{wins 32} {nominations 51} {text Nominated for 2 Oscars. Another 30 wins & 51 nominations.}]} {score 2.228306293487549}]
[{_id ObjectId("64de50da2932de4dd3204393")} {title how to train your dragon} {awards [{wins 32} {nominations 51}]} {score 2.228306293487549}]
[{_id ObjectID("573a13ccf29313caabd83281")} {title How to Train Your Dragon 2} {awards [{wins 18} {nominations 52} {text Nominated for 1 Oscar. Another 17 wins & 52 nominations.}]} {score 2.008449077606201}]
```

The results contain documents sorted regardless of the letter case. However, if you set `normalizer` to `none`, MongoDB Search returns the following results:

```shell
[{_id ObjectID("573a139cf29313caabcf662c")} {title Atomic Train} {awards [{wins 1} {nominations 1} {text 1 win & 1 nomination.}]} {score 3.3326687812805176}]
[{_id ObjectID("573a13bbf29313caabd52ff4")} {title How to Train Your Dragon} {awards [{wins 32} {nominations 51} {text Nominated for 2 Oscars. Another 30 wins & 51 nominations.}]} {score 2.2382168769836426}]
[{_id ObjectID("573a13ccf29313caabd83281")} {title How to Train Your Dragon 2} {awards [{wins 18} {nominations 52} {text Nominated for 1 Oscar. Another 17 wins & 52 nominations.}]} {score 2.0173802375793457}]
[{_id ObjectID("573a13b1f29313caabd36490")} {title Howard Zinn: You Can't Be Neutral on a Moving Train} {awards [{wins 1} {nominations 0} {text 1 win.}]} {score 1.446497917175293}]
[{_id ObjectID("573a13c8f29313caabd78a6b")} {title Last Train Home} {awards [{wins 14} {nominations 9} {text 14 wins & 9 nominations.}]} {score 2.8655927181243896}]
```

To sort your results without normalizing the letter case, set the `normalizer` option to `none` (on line 7) in your index definition, save the index definition, and rerun the query.

```java
import java.util.Arrays;
import static com.mongodb.client.model.Aggregates.limit;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Projections.*;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

public class CaseInsensitiveQuery {
  public static void main( String[] args ) {
    // define query
	    Document agg =
	        new Document("$search", 
	        	    new Document("index", "default")
	        	    .append("text", 
	        	    	new Document("path", "title")
	        	    	        .append("query", "train"))
	        	    	            .append("sort", 
	        	    	    new Document("title", 1)));

    // specify connection
    String uri = "<connection-string>";

    // establish connection and set namespace
    try (MongoClient mongoClient = MongoClients.create(uri)) {
      MongoDatabase database = mongoClient.getDatabase("sample_mflix");
      MongoCollection<Document> collection = database.getCollection("movies");
      
	  // run query and print results
      collection.aggregate(Arrays.asList(agg, 
        limit(5),
        project(fields(include("_id"), include("title"), include("awards"), computed("score", new Document("$meta", "searchScore"))))))
        .forEach(doc -> System.out.println(doc.toJson()));	
    }
  }
}

```

**Output:**

```json
{"_id": {"$oid": "573a139cf29313caabcf662c"}, "title": "Atomic Train", "awards": {"wins": 1, "nominations": 1, "text": "1 win & 1 nomination."}, "score": 3.317898988723755}
{"_id": {"$oid": "64de50ae2932de4dd3203061"}, "title": "atomic train", "awards": {"wins": 1, "nominations": 1}, "score": 3.317898988723755}
{"_id": {"$oid": "573a13bbf29313caabd52ff4"}, "title": "How to Train Your Dragon", "awards": {"wins": 32, "nominations": 51, "text": "Nominated for 2 Oscars. Another 30 wins & 51 nominations."}, "score": 2.228306293487549}
{"_id": {"$oid": "64de50da2932de4dd3204393"}, "title": "how to train your dragon", "awards": {"wins": 32, "nominations": 51}, "score": 2.228306293487549}
{"_id": {"$oid": "573a13ccf29313caabd83281"}, "title": "How to Train Your Dragon 2", "awards": {"wins": 18, "nominations": 52, "text": "Nominated for 1 Oscar. Another 17 wins & 52 nominations."}, "score": 2.008449077606201}
```

The results contain documents sorted regardless of the letter case. However, if you set `normalizer` to `none`, MongoDB Search returns the following results:

```shell
{"_id": {"$oid": "573a139cf29313caabcf662c"}, "title": "Atomic Train", "awards": {"wins": 1, "nominations": 1, "text": "1 win & 1 nomination."}, "score": 3.3326687812805176}
{"_id": {"$oid": "573a13bbf29313caabd52ff4"}, "title": "How to Train Your Dragon", "awards": {"wins": 32, "nominations": 51, "text": "Nominated for 2 Oscars. Another 30 wins & 51 nominations."}, "score": 2.2382168769836426}
{"_id": {"$oid": "573a13ccf29313caabd83281"}, "title": "How to Train Your Dragon 2", "awards": {"wins": 18, "nominations": 52, "text": "Nominated for 1 Oscar. Another 17 wins & 52 nominations."}, "score": 2.0173802375793457}
{"_id": {"$oid": "573a13b1f29313caabd36490"}, "title": "Howard Zinn: You Can't Be Neutral on a Moving Train", "awards": {"wins": 1, "nominations": 0, "text": "1 win."}, "score": 1.446497917175293}
{"_id": {"$oid": "573a13c8f29313caabd78a6b"}, "title": "Last Train Home", "awards": {"wins": 14, "nominations": 9, "text": "14 wins & 9 nominations."}, "score": 2.8655927181243896}
```

To sort your results without normalizing the letter case, set the `normalizer` option to `none` (on line 7) in your index definition, save the index definition, and rerun the query.

```kotlin
import com.mongodb.client.model.Aggregates.limit
import com.mongodb.client.model.Aggregates.project
import com.mongodb.client.model.Projections.*
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import org.bson.Document

fun main() {
    // establish connection and set namespace
    val uri = "<connection-string>"
    val mongoClient = MongoClient.create(uri)
    val database = mongoClient.getDatabase("sample_mflix")
    val collection = database.getCollection<Document>("movies")

    runBlocking {
        // define query
        val agg = Document(
            "\$search",
            Document("index", "default")
                .append(
                    "text",
                    Document("path", "title")
                        .append("query", "train")
                )
                .append(
                    "sort",
                    Document("title", 1)
                )
        )

        // run query and print results
        val resultsFlow = collection.aggregate<Document>(
            listOf(
                agg,
                limit(5),
                project(fields(
                    excludeId(),
                    include("title", "awards"),
                    computed("score", Document("\$meta", "searchScore"))
                ))
            )
        )
        resultsFlow.collect { println(it) }
    }
    mongoClient.close()
}

```

**Output:**

```javascript
Document{{title=atomic train, awards=Document{{wins=1, nominations=1}}, score=3.3326687812805176}}
Document{{title=Atomic Train, awards=Document{{wins=1, nominations=1, text=1 win & 1 nomination.}}, score=3.3326687812805176}}
Document{{title=how to train your dragon, awards=Document{{wins=32, nominations=51}}, score=2.2382168769836426}}
Document{{title=How to Train Your Dragon, awards=Document{{wins=32, nominations=51, text=Nominated for 2 Oscars. Another 30 wins & 51 nominations.}}, score=2.2382168769836426}}
Document{{title=How to Train Your Dragon 2, awards=Document{{wins=18, nominations=52, text=Nominated for 1 Oscar. Another 17 wins & 52 nominations.}}, score=2.0173802375793457}}
```

The results contain documents sorted regardless of the letter case. However, if you set `normalizer` to `none`, MongoDB Search returns the following results:

```none
Document{{title=Atomic Train, awards=Document{{wins=1, nominations=1, text=1 win & 1 nomination.}}, score=3.3326687812805176}}
Document{{title=How to Train Your Dragon, awards=Document{{wins=32, nominations=51, text=Nominated for 2 Oscars. Another 30 wins & 51 nominations.}}, score=2.2382168769836426}}
Document{{title=How to Train Your Dragon 2, awards=Document{{wins=18, nominations=52, text=Nominated for 1 Oscar. Another 17 wins & 52 nominations.}}, score=2.0173802375793457}}
Document{{title=Howard Zinn: You Can't Be Neutral on a Moving Train, awards=Document{{wins=1, nominations=0, text=1 win.}}, score=1.446497917175293}}
Document{{title=Last Train Home, awards=Document{{wins=14, nominations=9, text=14 wins & 9 nominations.}}, score=2.8655927181243896}}
```

To sort your results without normalizing the letter case, set the `normalizer` option to `none` (on line 7) in your index definition, save the index definition, and rerun the query.

```go
const { MongoClient } = require("mongodb");

// Replace the uri string with your MongoDB deployments connection string.
const uri =
  "<connection-string>";

const client = new MongoClient(uri);

async function run() {
  try {
    await client.connect();

    // set namespace
    const database = client.db("sample_mflix");
    const coll = database.collection("movies");

    // define pipeline
    const agg = [
        {
          '$search': {
            'index': 'default', 
            'text': { 'path': 'title', 'query': 'train' }, 
            'sort': { 'title': 1 }
          }
        }, {
          '$limit': 5
        }, {
          '$project': { '_id': 1, 'title': 1, 'awards': 1, 'score': { '$meta': 'searchScore' }}
        }
      ];
           
    // run pipeline
    const result = await coll.aggregate(agg);

    // print results
    await result.forEach((doc) => console.log(doc));
    
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

```

**Output:**

```json
{
  _id: new ObjectId("573a139cf29313caabcf662c"),
  title: 'Atomic Train',
  awards: { wins: 1, nominations: 1, text: '1 win & 1 nomination.' },
  score: 3.317898988723755
}
{
  _id: new ObjectId("64de50ae2932de4dd3203061"),
  title: 'atomic train',
  awards: { wins: 1, nominations: 1 },
 score: 3.317898988723755
}
{
  _id: new ObjectId("573a13bbf29313caabd52ff4"),
  title: 'How to Train Your Dragon',
  awards: {
    wins: 32,
    nominations: 51,
    text: 'Nominated for 2 Oscars. Another 30 wins & 51 nominations.'
  },
  score: 2.228306293487549
}
{
  _id: new ObjectId("64de50da2932de4dd3204393"),
  title: 'how to train your dragon',
  awards: { wins: 32, nominations: 51 },
  score: 2.228306293487549
}
{
  _id: new ObjectId("573a13ccf29313caabd83281"),
  title: 'How to Train Your Dragon 2',
  awards: {
    wins: 18,
    nominations: 52,
    text: 'Nominated for 1 Oscar. Another 17 wins & 52 nominations.'
  },
  score: 2.008449077606201
}
```

The results contain documents sorted regardless of the letter case. However, if you set `normalizer` to `none`, MongoDB Search returns the following results:

```shell
{
  _id: new ObjectId("573a139cf29313caabcf662c"),
  title: 'Atomic Train',
  awards: { wins: 1, nominations: 1, text: '1 win & 1 nomination.' },
  score: 3.3326687812805176
}
{
  _id: new ObjectId("573a13bbf29313caabd52ff4"),
  title: 'How to Train Your Dragon',
  awards: {
    wins: 32,
    nominations: 51,
    text: 'Nominated for 2 Oscars. Another 30 wins & 51 nominations.'
  },
  score: 2.2382168769836426
}
{
  _id: new ObjectId("573a13ccf29313caabd83281"),
  title: 'How to Train Your Dragon 2',
  awards: {
    wins: 18,
    nominations: 52,
    text: 'Nominated for 1 Oscar. Another 17 wins & 52 nominations.'
  },
  score: 2.0173802375793457
}
{
  _id: new ObjectId("573a13b1f29313caabd36490"),
  title: "Howard Zinn: You Can't Be Neutral on a Moving Train",
  awards: { wins: 1, nominations: 0, text: '1 win.' },
  score: 1.446497917175293
}
{
  _id: new ObjectId("573a13c8f29313caabd78a6b"),
  title: 'Last Train Home',
  awards: { wins: 14, nominations: 9, text: '14 wins & 9 nominations.' },
  score: 2.8655927181243896
}
```

To sort your results without normalizing the letter case, set the `normalizer` option to `none` (on line 7) in your index definition, save the index definition, and rerun the query.

```go
import pymongo

# connect to your Atlas cluster
client = pymongo.MongoClient('<connection-string>')

# define pipeline
pipeline = [
    {
        '$search': {
            'index': 'default', 
            'text': { 'path': 'title', 'query': 'train' }, 
            'sort': { 'title': 1 }
        }
    }, {
        '$limit': 5
    }, {
        '$project': { '_id': 1, 'title': 1, 'awards': 1, 'score': { '$meta': 'searchScore' } }
    }
]

# run pipeline
result = client['sample_mflix']['movies'].aggregate(pipeline)

# print results
for i in result:
    print(i)

```

**Output:**

```json
{'_id': ObjectId('573a139cf29313caabcf662c'), 'title': 'Atomic Train', 'awards': {'wins': 1, 'nominations': 1, 'text': '1 win & 1 nomination.'}, 'score': 3.317898988723755}
{'_id': ObjectId('64de50ae2932de4dd3203061'), 'title': 'atomic train', 'awards': {'wins': 1, 'nominations': 1}, 'score': 3.317898988723755}
{'_id': ObjectId('573a13bbf29313caabd52ff4'), 'title': 'How to Train Your Dragon', 'awards': {'wins': 32, 'nominations': 51, 'text': 'Nominated for 2 Oscars. Another 30 wins & 51 nominations.'}, 'score': 2.228306293487549}
{'_id': ObjectId('64de50da2932de4dd3204393'), 'title': 'how to train your dragon', 'awards': {'wins': 32, 'nominations': 51}, 'score': 2.228306293487549}
{'_id': ObjectId('573a13ccf29313caabd83281'), 'title': 'How to Train Your Dragon 2', 'awards': {'wins': 18, 'nominations': 52, 'text': 'Nominated for 1 Oscar. Another 17 wins & 52 nominations.'}, 'score': 2.008449077606201}
```

The results contain documents sorted regardless of the letter case. However, if you set `normalizer` to `none`, MongoDB Search returns the following results:

```shell
{'_id': ObjectId('573a139cf29313caabcf662c'), 'title': 'Atomic Train', 'awards': {'wins': 1, 'nominations': 1, 'text': '1 win & 1 nomination.'}, 'score': 3.3326687812805176}
{'_id': ObjectId('573a13bbf29313caabd52ff4'), 'title': 'How to Train Your Dragon', 'awards': {'wins': 32, 'nominations': 51, 'text': 'Nominated for 2 Oscars. Another 30 wins & 51 nominations.'}, 'score': 2.2382168769836426}
{'_id': ObjectId('573a13ccf29313caabd83281'), 'title': 'How to Train Your Dragon 2', 'awards': {'wins': 18, 'nominations': 52, 'text': 'Nominated for 1 Oscar. Another 17 wins & 52 nominations.'}, 'score': 2.0173802375793457}
{'_id': ObjectId('573a13b1f29313caabd36490'), 'title': "Howard Zinn: You Can't Be Neutral on a Moving Train", 'awards': {'wins': 1, 'nominations': 0, 'text': '1 win.'}, 'score': 1.446497917175293}
{'_id': ObjectId('573a13c8f29313caabd78a6b'), 'title': 'Last Train Home', 'awards': {'wins': 14, 'nominations': 9, 'text': '14 wins & 9 nominations.'}, 'score': 2.8655927181243896}
```

To sort your results without normalizing the letter case, set the `normalizer` option to `none` (on line 7) in your index definition, save the index definition, and rerun the query.

### Sort by ObjectId

The following query uses the [range](https://www.mongodb.com/docs/search/query/operators-collectors/range.md#std-label-range-ref) operator to search the the `released` field in the `sample_mflix.movies` collection for movies released between `2015-01-01` and `2015-12-31`. It sorts the results by the `_id` field, which contains value of type `ObjectId`, in descending order.

```json
db.movies.aggregate([
  {
    "$search": {
      "range": {
        "path": "released",
        "gt": ISODate("2015-01-01T00:00:00.000Z"),
        "lt": ISODate("2015-12-31T00:00:00.000Z")
      },
      "sort": {
        "_id": -1
      }
    }
  },
  {
    "$limit": 5
  },
  {
    "$project": {
      "_id": 1,
      "title": 1,
      "released": 1,
      "score": { "$meta": "searchScore" }
    }
  }
])
```

**Output:**

```json
[
  {
    _id: ObjectId('573a13fbf29313caabdedf31'),
    title: 'No Home Movie',
    released: ISODate('2015-08-10T00:00:00.000Z'),
    score: 1
  },
  {
    _id: ObjectId('573a13fbf29313caabdedf30'),
    title: 'Our Loved Ones',
    released: ISODate('2015-08-12T00:00:00.000Z'),
    score: 1
  },
  {
    _id: ObjectId('573a13faf29313caabded406'),
    title: 'The Red Spider',
    released: ISODate('2015-11-20T00:00:00.000Z'),
    score: 1
  },
  {
    _id: ObjectId('573a13faf29313caabded1d6'),
    title: 'The Laundryman',
    released: ISODate('2015-07-11T00:00:00.000Z'),
    score: 1
  },
  {
    _id: ObjectId('573a13faf29313caabdecaf3'),
    title: 'Right Now, Wrong Then',
    released: ISODate('2015-09-01T00:00:00.000Z'),
    score: 1
  }
]
```

### Sort by UUID

The following query searches for the term `hello` in field `b` in the `users` collection. The query sorts the results by field `a`, which contains polymorphic data (to demonstrate the sort order), in ascending order.

```json
db.users.aggregate([
  {
    "$search": {
      "text": {
        "path": "b",
        "query": "hello"
      },
      "sort": {
        "a": 1
      }
    }
  },
  {
    "$project": {
      "_id": 1,
      "a": 1,
      "score": { "$meta": "searchScore" }
    }
  }
])
```

**Output:**

```json
[
  { _id: 3, score: 0.029335692524909973 },
  {
    _id: 0,
    a: UUID('1a324de2-e34b-c87e-f2a1-42ce37ad74ed'),
    score: 0.029335692524909973
  },
  {
    _id: 1,
    a: UUID('3b241101-e2bb-4255-8caf-4136c566a962'),
    score: 0.029335692524909973
  },
  {
    _id: 6,
    a: UUID('7eeddf21-b313-4a5c-81c2-c68915daa618'),
    score: 0.029335692524909973
  },
  {
    _id: 4,
    a: UUID('d3c12e1c-c36e-25ed-7c3e-1e7f1e53c752'),
    score: 0.029335692524909973
  },
  {
    _id: 5,
    a: UUID('d73f181e-cdda-42b4-b844-4d6e172e9bc8'),
    score: 0.029335692524909973
  },
  {
    _id: 2,
    a: UUID('dee11d4e-63c6-4d90-983c-5c9f1e79e96c'),
    score: 0.029335692524909973
  }
]
```

### Sort by Null Values

Consider the following queries that search field `b` for the string `hello` in the `users` collection using the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref) operator. The query then sorts the results by field `c`, which contains null or missing values for some documents in the collection.

To learn more, see [Sort by Null and Missing Values.](https://www.mongodb.com/docs/search/query/sort.md#std-label-fts-sort-null)

#### Ascending Sort (Default)

During an ascending sort, MongoDB Search returns documents with null or missing values at the top of the results by default, as shown in the following example:

```json
db.users.aggregate([
  {
    "$search": {
      "text": {
        "path": "b",
        "query": "hello"
      },
      "sort": { "c": 1 }
    }
  },
  {
    "$project": {
      "_id": 1,
      "c": 1,
      "score": { "$meta": "searchScore" }
    }
  }
])
```

**Output:**

```js
[
  { _id: 4, c: null, score: 0.029335692524909973 },
  { _id: 5, c: [], score: 0.029335692524909973 },
  { _id: 6, score: 0.029335692524909973 },
  { _id: 2, c: 'foo', score: 0.029335692524909973 },
  {
    _id: 3,
    c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
    score: 0.029335692524909973
  },
  {
    _id: 0,
    c: ObjectId('507f1f77bcf86cd799439011'),
    score: 0.029335692524909973
  },
  { _id: 1, c: true, score: 0.029335692524909973 }
]

```

#### Descending Sort (Default)

During a descending sort, MongoDB Search returns documents with null or missing values at the bottom of the results by default, as shown in the following example:

```json
db.users.aggregate([
  {
    "$search": {
      "text": {
        "path": "b",
        "query": "hello"
      },
      "sort": { "c": -1 }
    }
  },
  {
    "$project": {
      "_id": 1,
      "c": 1,
      "score": { "$meta": "searchScore" }
    }
  }
])
```

**Output:**

```js
[
  { _id: 1, c: true, score: 0.025981096550822258 },
  {
    _id: 0,
    c: ObjectId('507f1f77bcf86cd799439011'),
    score: 0.025981096550822258
  },
  {
    _id: 3,
    c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
    score: 0.025981096550822258
  },
  { _id: 2, c: 'foo', score: 0.025981096550822258 },
  { _id: 4, c: null, score: 0.025981096550822258 },
  { _id: 5, c: [], score: 0.025981096550822258 },
  { _id: 6, score: 0.025981096550822258 }
]

```

**Note:**

Setting `noData: lowest` is the same as the default.

#### Ascending Sort (noData: lowest)

If you specify the `noData` field as `lowest` during an ascending sort, MongoDB Search returns documents with null or missing values at the top of the results, as shown in the following example.

```json
db.users.aggregate([
  {
    "$search": {
      "text": {
        "path": "b",
        "query": "hello"
      },
      "sort": {
        "c": {
          "order": 1,
          "noData": "lowest"
        }
      }
    }
  },
  {
    "$project": {
      "_id": 1,
      "c": 1,
      "score": { "$meta": "searchScore" }
    }
  }
])
```

**Output:**

```js
[
  { _id: 4, c: null, score: 0.029335692524909973 },
  { _id: 5, c: [], score: 0.029335692524909973 },
  { _id: 6, score: 0.029335692524909973 },
  { _id: 2, c: 'foo', score: 0.029335692524909973 },
  {
    _id: 3,
    c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
    score: 0.029335692524909973
  },
  {
    _id: 0,
    c: ObjectId('507f1f77bcf86cd799439011'),
    score: 0.029335692524909973
  },
  { _id: 1, c: true, score: 0.029335692524909973 }
]

```

#### Descending Sort (noData: lowest)

If you specify the `noData` field as `lowest` during a descending sort, MongoDB Search returns documents with null or missing values at the bottom of the results, as shown in the following example.

```json
db.users.aggregate([
  {
    "$search": {
      "text": {
        "path": "b",
        "query": "hello"
      },
      "sort": {
        "c": {
          "order": -1,
          "noData": "lowest"
        }
      }
    }
  },
  {
    "$project": {
      "_id": 1,
      "c": 1,
      "score": { "$meta": "searchScore" }
    }
  }
])
```

**Output:**

```js
[
  { _id: 1, c: true, score: 0.025981096550822258 },
  {
    _id: 0,
    c: ObjectId('507f1f77bcf86cd799439011'),
    score: 0.025981096550822258
  },
  {
    _id: 3,
    c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
    score: 0.025981096550822258
  },
  { _id: 2, c: 'foo', score: 0.025981096550822258 },
  { _id: 4, c: null, score: 0.025981096550822258 },
  { _id: 5, c: [], score: 0.025981096550822258 },
  { _id: 6, score: 0.025981096550822258 }
]

```

#### Ascending Sort (noData: highest)

If you specify the `noData` field as `highest` during an ascending sort, MongoDB Search returns documents with null or missing values at the bottom of the results, as shown in the following example.

```json
db.users.aggregate([
  {
    "$search": {
      "text": {
        "path": "b",
        "query": "hello"
      },
      "sort": {
        "c": {
          "order": 1,
          "noData": "highest"
        }
      }
    }
  },
  {
    "$project": {
      "_id": 1,
      "c": 1,
      "score": { "$meta": "searchScore" }
    }
  }
])
```

**Output:**

```js
[
  { _id: 2, c: 'foo', score: 0.025981096550822258 },
  {
    _id: 3,
    c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
    score: 0.025981096550822258
  },
  {
    _id: 0,
    c: ObjectId('507f1f77bcf86cd799439011'),
    score: 0.025981096550822258
  },
  { _id: 1, c: true, score: 0.025981096550822258 },
  { _id: 4, c: null, score: 0.025981096550822258 },
  { _id: 5, c: [], score: 0.025981096550822258 },
  { _id: 6, score: 0.025981096550822258 }
]
```

#### Descending Sort (noData: highest)

If you specify the `noData` field as `highest` during a descending sort, MongoDB Search returns documents with null or missing values at the top of the results, as shown in the following example.

```json
db.users.aggregate([
  {
    "$search": {
      "text": {
        "path": "b",
        "query": "hello"
      },
      "sort": {
        "c": {
          "order": -1,
          "noData": "highest"
        }
      }
    }
  },
  {
    "$project": {
      "_id": 1,
      "c": 1,
      "score": { "$meta": "searchScore" }
    }
  }
])
```

**Output:**

```js
[
  { _id: 4, c: null, score: 0.025981096550822258 },
  { _id: 5, c: [], score: 0.025981096550822258 },
  { _id: 6, score: 0.025981096550822258 },
  { _id: 1, c: true, score: 0.025981096550822258 },
  {
    _id: 0,
    c: ObjectId('507f1f77bcf86cd799439011'),
    score: 0.025981096550822258
  },
  {
    _id: 3,
    c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
    score: 0.025981096550822258
  },
  { _id: 2, c: 'foo', score: 0.025981096550822258 }
]
```

The order of documents with `"_id": 4`, `"_id": 5`, and `"_id": 6` is random because MongoDB Search treats null and missing values as equal when sorting.

### Sort on Multi-Typed Arrays

Consider the following queries on the [users collection](https://www.mongodb.com/docs/search/query/sort.md#std-label-fts-sort-index) given an additional document with a multi-typed array in field `c`:

```json
db.users.insertOne({
  "_id": 7,
  "a": UUID("03e32aa9-1cbd-43b8-b9d6-18b171a03cc7"),
  "b": "hello",
  "c": [ false, null, 15 ]
})
```

The following queries search field `b` for the string `hello` using the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref) operator and sorts the results by field `c`.

**Note:**

Setting `noData: lowest` in your [sort syntax](https://www.mongodb.com/docs/search/query/sort.md#std-label-sort-syntax-ref) is the same as the default.

#### Ascending Sort (Default)

For an ascending sort, MongoDB Search uses the element with the lowest BSON (Binary Javascript Object Notation) type to represent the multi-typed array. By default, MongoDB Search considers null or missing values as the lowest BSON (Binary Javascript Object Notation) value. Therefore, MongoDB Search uses `null` to represent the multi-typed array for the document with `_id: 7` and returns this document at the top of the results along with other null and missing values.

To learn more, see [Sort by Null and Missing Values](https://www.mongodb.com/docs/search/query/sort.md#std-label-fts-sort-null) and [Sort Arrays with Multiple Types.](https://www.mongodb.com/docs/search/query/sort.md#std-label-fts-sort-arrays-multiple-types)

```json
db.users.aggregate([
  {
    "$search": {
      "text": {
        "path": "b",
        "query": "hello"
      },
      "sort": {
        "c": 1
      }
    }
  },
  {
    "$project": {
      "_id": 1,
      "c": 1,
      "score": { "$meta": "searchScore" }
    }
  }
])
```

**Output:**

```js
[
  { _id: 4, c: null, score: 0.025981096550822258 },
  { _id: 5, c: [], score: 0.025981096550822258 },
  { _id: 6, score: 0.025981096550822258 }
  { _id: 7, c: [ false, null, 15 ], score: 0.025981096550822258 },
  { _id: 2, c: 'foo', score: 0.025981096550822258 },
  {
    _id: 3,
    c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
    score: 0.025981096550822258
  },
  {
    _id: 0,
    c: ObjectId('507f1f77bcf86cd799439011'),
    score: 0.025981096550822258
  },
  { _id: 1, c: true, score: 0.025981096550822258 }
]
```

The order of documents with `"_id": 4`, `"_id": 5`, `"_id": 6`, and `"_id": 7` is random because MongoDB Search treats null and missing values as equal when sorting.

#### Descending Sort (Default)

For a descending sort, MongoDB Search uses the element with the highest BSON (Binary Javascript Object Notation) type to represent the multi-typed array. MongoDB Search uses `false` to represent the multi-typed array for the document with `_id: 7`, as this is the highest BSON (Binary Javascript Object Notation) type in the array. Since MongoDB Search also ranks `true` values above `false` values, MongoDB Search returns this document after the document with `_id: 1`.

To learn more, see [Sort by Null and Missing Values](https://www.mongodb.com/docs/search/query/sort.md#std-label-fts-sort-null) and [Sort Arrays with Multiple Types.](https://www.mongodb.com/docs/search/query/sort.md#std-label-fts-sort-arrays-multiple-types)

```json
db.users.aggregate([
  {
    "$search": {
      "text": {
        "path": "b",
        "query": "hello"
      },
      "sort": {
        "c": -1
      }
    }
  },
  {
    "$project": {
      "_id": 1,
      "c": 1,
      "score": { "$meta": "searchScore" }
    }
  }
])
```

**Output:**

```js
[
  { _id: 1, c: true, score: 0.025981096550822258 },
  { _id: 7, c: [ false, null, 15 ], score: 0.025981096550822258 },
  {
    _id: 0,
    c: ObjectId('507f1f77bcf86cd799439011'),
    score: 0.025981096550822258
  },
  {
    _id: 3,
    c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
    score: 0.025981096550822258
  },
  { _id: 2, c: 'foo', score: 0.025981096550822258 }
  { _id: 4, c: null, score: 0.025981096550822258 },
  { _id: 5, c: [], score: 0.025981096550822258 },
  { _id: 6, score: 0.025981096550822258 },
]
```

The order of documents with `"_id": 4`, `"_id": 5`, and `"_id": 6` is random because MongoDB Search treats null and missing values as equal when sorting.

The following queries specify `noData: highest` to set null values as the highest BSON (Binary Javascript Object Notation) type during sorting.

#### Ascending Sort (noData: highest)

For an ascending sort, MongoDB Search uses the element with the lowest BSON (Binary Javascript Object Notation) type to represent the multi-typed array. The query specifies `noData: highest` to consider null or missing values as the highest BSON (Binary Javascript Object Notation) value, so MongoDB Search uses `15` to represent the multi-typed array for the document with `_id: 7` since numbers are the next lowest BSON (Binary Javascript Object Notation) type in the array.

To learn more, see [Sort by Null and Missing Values](https://www.mongodb.com/docs/search/query/sort.md#std-label-fts-sort-null) and [Sort Arrays with Multiple Types.](https://www.mongodb.com/docs/search/query/sort.md#std-label-fts-sort-arrays-multiple-types)

```json
db.users.aggregate([
  {
    "$search": {
      "text": {
        "path": "b",
        "query": "hello"
      },
      "sort": {
        "c": {
          "order": 1,
          "noData": "highest"
        }
      }
    }
  },
  {
    "$project": {
      "_id": 1,
      "c": 1,
      "score": { "$meta": "searchScore" }
    }
  }
])
```

**Output:**

```js
[
  { _id: 7, c: [ false, null, 15 ], score: 0.025981096550822258 },
  { _id: 2, c: 'foo', score: 0.025981096550822258 },
  {
    _id: 3,
    c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
    score: 0.025981096550822258
  },
  {
    _id: 0,
    c: ObjectId('507f1f77bcf86cd799439011'),
    score: 0.025981096550822258
  },
  { _id: 1, c: true, score: 0.025981096550822258 },
  { _id: 4, c: null, score: 0.025981096550822258 },
  { _id: 5, c: [], score: 0.025981096550822258 },
  { _id: 6, score: 0.025981096550822258 }
]
```

The order of documents with `"_id": 4`, `"_id": 5`, and `"_id": 6` is random because MongoDB Search treats null and missing values as equal when sorting.

#### Descending Sort (noData: highest)

For a descending sort, MongoDB Search uses the element with the highest BSON (Binary Javascript Object Notation) type to represent the multi-typed array. Since the query specifies the `noData` field as `highest` to set null or missing values as the highest BSON (Binary Javascript Object Notation) value, MongoDB Search uses `null` to represent the multi-typed array for the document with `_id: 7` and returns this document at the top of the results along with other null and missing values.

To learn more, see [Sort by Null and Missing Values](https://www.mongodb.com/docs/search/query/sort.md#std-label-fts-sort-null) and [Sort Arrays with Multiple Types.](https://www.mongodb.com/docs/search/query/sort.md#std-label-fts-sort-arrays-multiple-types)

```json
db.users.aggregate([
  {
    "$search": {
      "text": {
        "path": "b",
        "query": "hello"
      },
      "sort": {
        "c": {
          "order": -1,
          "noData": "highest"
        }
      }
    }
  },
  {
    "$project": {
      "_id": 1,
      "c": 1,
      "score": { "$meta": "searchScore" }
    }
  }
])
```

**Output:**

```js
[
  { _id: 4, c: null, score: 0.025981096550822258 },
  { _id: 5, c: [], score: 0.025981096550822258 },
  { _id: 6, score: 0.025981096550822258 },
  { _id: 7, c: [ false, null, 15 ], score: 0.025981096550822258 },
  { _id: 1, c: true, score: 0.025981096550822258 },
  {
    _id: 0,
    c: ObjectId('507f1f77bcf86cd799439011'),
    score: 0.025981096550822258
  },
  {
    _id: 3,
    c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
    score: 0.025981096550822258
  },
  { _id: 2, c: 'foo', score: 0.025981096550822258 }
]
```

The order of documents with `"_id": 4`, `"_id": 5`, `"_id": 6`, and `"_id": 7` is random because MongoDB Search treats null and missing values as equal when sorting.

### Sort by Boolean

The following query searches the `sample_airbnb.listingsAndReviews` collection for properties in `Portugal` and sorts the results in descending order by the `boolean` field `is_location_exact`.

The query uses the [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage to limit the output to `5` documents. It also uses the [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to omit all fields except `name`, `property_type`, `address.country`, and `address.location.is_location_exact` in the results.

```json
db.listingsAndReviews.aggregate([
  {
    "$search": {
      "text": {
        "path": "address.country",
        "query": "Portugal"
      },
      "sort": {
        "address.location.is_location_exact": -1,
      }
    }
  },
  {
    "$limit": 5
  },
  {
    "$project": {
      "_id": 0,
      "name": 1,
      "property_type": 1,
      "address.country": 1,
      "address.location.is_location_exact": 1
    }
  }
])
```

**Output:**

```javascript
[
  {
    name: 'BBC OPORTO 4X2',
    property_type: 'Apartment',
    address: { country: 'Portugal', location: { is_location_exact: true } }
  },
  {
    name: 'Heroísmo IV',
    property_type: 'Apartment',
    address: { country: 'Portugal', location: { is_location_exact: true } }
  },
  {
    name: 'Spacious and well located apartment',
    property_type: 'Apartment',
    address: { country: 'Portugal', location: { is_location_exact: true } }
  },
  {
    name: 'Renovated Classic Design Studio with Sun Room',
    property_type: 'Apartment',
    address: { country: 'Portugal', location: { is_location_exact: true } }
  },
  {
    name: "O'Porto Studio | Historic Center",
    property_type: 'Loft',
    address: { country: 'Portugal', location: { is_location_exact: true } }
  }
]
```

In the preceding results, the value of `is_location_exact` is `true` for the documents because in a descending sort, MongoDB Search ranks `true` values above `false` values. If you do an ascending sort by changing the value on line 9 of the preceding query to `1`, MongoDB Search ranks the documents with `false` values higher than `true` values and returns the following documents:

```json
[
  {
    name: 'Ribeira Charming Duplex',
    property_type: 'House',
    address: { country: 'Portugal', location: { is_location_exact: false } }
  },
  {
    name: 'Be Happy in Porto',
    property_type: 'Loft',
    address: { country: 'Portugal', location: { is_location_exact: false } }
  },
  {
    name: 'Downtown Oporto Inn (room cleaning)',
    property_type: 'Hostel',
    address: { country: 'Portugal', location: { is_location_exact: false } }
  },
  {
    name: 'A Casa Alegre é um apartamento T1.',
    property_type: 'Apartment',
    address: { country: 'Portugal', location: { is_location_exact: false } }
  },
  {
    name: 'FloresRooms 3T',
    property_type: 'Apartment',
    address: { country: 'Portugal', location: { is_location_exact: false } }
  }
]
```

### Compound Search and Sort

The following query uses the [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage to do the following:

- Search for movies that have the term `dance` in the title, with a preference for movies that have won 2 or more awards and were released after 01 January, 1990.

- Sort the results by the number of awards in descending order, then by the movie title in ascending order, and then by the release date in descending order.

The query uses the [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage to limit the output to `10` documents. It also uses the [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to do the following:

- Omit all fields except `title`, `released`, and `awards.wins` in the results.

- Add a field named `score`.

```json
db.movies.aggregate([
  {
    "$search": {
      "compound": {
        "must": [{
          "text": {
            "path": "title",
            "query": "dance"
          }
        }],
        "should": [{
          "range": {
            "path": "awards.wins",
            "gte": 2
          }
        }, {
          "range": {
            "path": "released",
            "gte": ISODate("1990-01-01T00:00:00.000Z")
          }
        }]
      },
      "sort": {
        "awards.wins": -1,
        "title": 1,
        "released": -1
      }
    }
  },
  {
    "$limit": 10
  },
  {
    "$project": {
      "_id": 0,
      "title": 1,
      "released": 1,
      "awards.wins": 1,
      "score": { "$meta": "searchScore" }
    }
  }
])
```

**Output:**

```json
[
  {
    title: 'Shall We Dance?',
    released: ISODate("1997-07-11T00:00:00.000Z"),
    awards: { wins: 57 },
    score: 4.9811458587646484
  },
  {
    title: 'Shall We Dance?',
    released: ISODate("1997-07-11T00:00:00.000Z"),
    awards: { wins: 57 },
    score: 4.9811458587646484
  },
  {
    title: 'War Dance',
    released: ISODate("2008-11-01T00:00:00.000Z"),
    awards: { wins: 11 },
    score: 5.466421127319336
  },
  {
    title: 'Dance with the Devil',
    released: ISODate("1997-10-31T00:00:00.000Z"),
    awards: { wins: 6 },
    score: 4.615056037902832
  },
  {
    title: 'Save the Last Dance',
    released: ISODate("2001-01-12T00:00:00.000Z"),
    awards: { wins: 6 },
    score: 4.615056037902832
  },
  {
    title: 'Dance with a Stranger',
    released: ISODate("1985-08-09T00:00:00.000Z"),
    awards: { wins: 4 },
    score: 3.615056037902832
  },
  {
    title: 'The Baby Dance',
    released: ISODate("1998-08-23T00:00:00.000Z"),
    awards: { wins: 4 },
    score: 4.981145858764648
  },
  {
    title: 'Three-Step Dance',
    released: ISODate("2004-02-19T00:00:00.000Z"),
    awards: { wins: 4 },
    score: 4.981145858764648
  },
  {
    title: "Cats Don't Dance",
    released: ISODate("1997-03-26T00:00:00.000Z"),
    awards: { wins: 3 },
    score: 4.981145858764648
  },
  {
    title: 'Dance Me Outside',
    released: ISODate("1995-03-10T00:00:00.000Z"),
    awards: { wins: 3 },
    score: 4.981145858764648
  }
]
```

### Facet Search and Sort

The following query uses the [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage to do the following:

- Search for movies released between 01 January, 2010 and 01, January, 2015 using the [range](https://www.mongodb.com/docs/search/query/operators-collectors/range.md#std-label-range-ref) operator.

- Get a count of the number of movies that won `1`, `5`, `10`, and `15` awards.

- Get a count of the number of movies released on `2010-01-01`, `2011-01-01`, `2012-01-01`, `2013-01-01`, `2014-01-01`, and `2015-01-01`.

- Sort the results in descending order of released date using the `sort` option.

The query uses the [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage to do the following:

- Limit the output to `5` documents in the `docs` output field.

- Limit the output to `1` document in the `meta` output field.

It uses the [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to omit all fields except the `awards.wins`, `released`, and `title` fields.

It also uses the [`$replaceWith`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/replaceWith.md#mongodb-pipeline-pipe.-replaceWith) stage to include the metadata results stored in the `$$SEARCH_META` variable in the `meta` output field and the [`$set`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/set.md#mongodb-pipeline-pipe.-set) stage to add the `meta` field to the results.

```json
db.movies.aggregate([
  {
    "$search": {
      "facet": {
        "operator": {
          "range": {
            "path": "released",
            "gt": ISODate("2010-01-01T00:00:00.000Z"),
            "lt": ISODate("2015-01-01T00:00:00.000Z")
          }
        },
        "facets": {
          "awardsFacet": {
            "type": "number",
            "path": "awards.wins",
            "boundaries" : [1,5,10,15]
          },
          "releasedFacet" : {
            "type" : "date",
            "path" : "released",
            "boundaries" : [ISODate("2010-01-01T00:00:00.000Z"), ISODate("2011-01-01T00:00:00.000Z"), ISODate("2012-01-01T00:00:00.000Z"), ISODate("2013-01-01T00:00:00.000Z"), ISODate("2014-01-01T00:00:00.000Z"), ISODate("2015-01-01T00:00:00.000Z")]
          }
        }
      },
      "sort": {
        "released": -1
      }
    }
  },
  {
    "$facet": {
      "docs": [
        { "$limit": 5 },
        { "$project":
          {
            "_id": 0,
            "title": 1,
            "released": 1,
            "awards.wins": 1
          }
        }
      ],
      "meta": [
        {"$replaceWith": "$$SEARCH_META"},
        {"$limit": 1}
      ]
    }
  },
  {
    "$set": {
      "meta": {
        "$arrayElemAt": ["$meta", 0]
      }
    }
  }
])
```

**Output:**

```json
[
  {
    docs: [
      {
        title: 'Cold in July',
        released: ISODate("2014-12-31T00:00:00.000Z"),
        awards: { wins: 1 }
      },
      {
        title: 'The Gambler',
        released: ISODate("2014-12-31T00:00:00.000Z"),
        awards: { wins: 7 }
      },

      {
        title: 'Force Majeure',
        released: ISODate("2014-12-30T00:00:00.000Z"),
        awards: { wins: 31 }
      },
      {
        title: 'LFO',
        released: ISODate("2014-12-27T00:00:00.000Z"),
        awards: { wins: 3 }
      },
      {
        title: 'Peace After Marriage',
        released: ISODate('2014-12-26T00:00:00.000Z'),
        awards: { wins: 5 }
      }
    ],
    meta: {
      count: { lowerBound: Long("4821") },
        facet: {
          releasedFacet: {
            buckets: [
              {
                _id: ISODate("2010-01-01T00:00:00.000Z"),
                count: Long("857")
              },
              {
                _id: ISODate("2011-01-01T00:00:00.000Z"),
                count: Long("909")
              },
              {
                _id: ISODate("2012-01-01T00:00:00.000Z"),
                count: Long("903")
              },
              {
                _id: ISODate("2013-01-01T00:00:00.000Z"),
                count: Long("1063")
              },
              {
                _id: ISODate("2014-01-01T00:00:00.000Z"),
                count: Long("1089")
              }
            ]
          },
          awardsFacet: {
            buckets: [
              { _id: 1, count: Long("2330") },
              { _id: 5, count: Long("604") },
              { _id: 10, count: Long("233") }
            ]
          }
        }
      }
    }
  }
]
```

### Sort by Score

The following examples demonstrate how to sort the results by the score of the documents in the results. The examples demonstrate how to perform the following actions:

- Retrieve the lowest scoring documents first by sorting the results in ascending order.

- Sort the results by score in descending order and for results with identical scores, sort arbitrarily.

- Sort the results by score and for results with identical scores, sort using a unique field.

#### Ascending Sort

The following query uses the [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage to perform the following actions:

- Search for movies that have the term `story` in the title.

- Sort the results by score in ascending order.

The query uses the [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage to limit the output to `5` documents. It also uses the [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to perform the following actions:

- Omit all fields except `title` in the results.

- Add a field named `score`.

```json
db.movies.aggregate([
  {
    "$search": {
      "text": {
        "path": "title",
        "query": "story"
      },
      "sort": {score: {$meta: "searchScore", order: 1}}
    }
  },
  {
    "$limit": 5
  },
  {
    "$project": {
      "_id": 0,
      "title": 1,
      "score": {$meta: "searchScore"}
    }
  }
])
```

**Output:**

```json
[
  {
    title: 'Do You Believe in Miracles? The Story of the 1980 U.S. Hockey Team',
    score: 0.8674521446228027
  },
  {
    title: 'Once in a Lifetime: The Extraordinary Story of the New York Cosmos',
    score: 0.9212141036987305
  },
  {
    title: 'The Source: The Story of the Beats and the Beat Generation',
    score: 0.9820802211761475
  },
  {
    title: 'If These Knishes Could Talk: The Story of the NY Accent',
    score: 0.9820802211761475
  },
  {
    title: 'Dream Deceivers: The Story Behind James Vance vs. Judas Priest',
    score: 1.051558256149292
  }
]
```

#### Default (Descending) Sort

The following query uses the [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage to perform the following actions:

- Search for movies that have the term `summer` in the title.

- Sort the results by score in descending order and for results with identical scores, sort arbitrarily.

The query uses the [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage to limit the output to `5` documents. It also uses the [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to perform the following actions:

- Omit all fields except `_id` and `title` in the results.

- Add a field named `score`.

```json
db.movies.aggregate([
  {
    "$search": {
      "text": {
        "path": "title",
        "query": "summer"
      },
      "sort": {score: {$meta: "searchScore"}}
    }
  },
  {
    "$limit": 5
  },
  {
    "$project": {
      "_id": 1,
      "title": 1,
      "score": {$meta: "searchScore"}
    }
  }
])
```

**Output:**

```json
[
  {
    _id: ObjectId("573a1398f29313caabcea21e"),
    title: 'Summer',
    score: 3.5844719409942627
  },
  {
    _id: ObjectId("573a13a6f29313caabd18eca"),
    title: 'Summer Things',
    score: 3.000213623046875
  },
  {
    _id: ObjectId("573a13b8f29313caabd4c1d0"),
    title: 'Summer Palace',
    score: 3.000213623046875
  },
  {
    _id: ObjectId("573a1394f29313caabcde8e8"),
    title: 'Summer Stock',
    score: 3.000213623046875
  },
  {
    _id: ObjectId("573a13acf29313caabd284fa"),
    title: 'Wolf Summer',
    score: 3.000213623046875
  }
]
```

#### Sort by Unique Field

The following query uses the [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage to perform the following actions:

- Search for movies that have the term `prince` in the title.

- Sort the results first by score and then by the value of the `released` field in ascending order for results with identical scores.

The query uses the [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage to limit the output to `5` documents. It also uses the [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to perform the following actions:

- Omit all fields except `title` and `released` in the results.

- Add a field named `score`.

```json
db.movies.aggregate([
  {
    "$search": {
      "text": {
        "path": "title",
        "query": "prince"
      },
      "sort": {score: {$meta: "searchScore"}, "released": 1}
    }
  },
  {
    "$limit": 5
  },
  {
    "$project": {
      "_id": 0,
      "title": 1,
      "released": 1,
      "score": {$meta: "searchScore"}
    }
  }
])
```

**Output:**

```json
[
  {
    title: 'Prince',
    released: ISODate("2015-08-14T00:00:00.000Z"),
    score: 4.168826103210449
  },
  {
    title: 'Prince Avalanche',
    released: ISODate("2013-09-19T00:00:00.000Z"),
    score: 3.4893198013305664
  },
  {
    title: 'The Prince',
    released: ISODate("2014-08-22T00:00:00.000Z"),
    score: 3.4893198013305664
  },
  {
    title: 'Prince of Foxes',
    released: ISODate("1949-12-23T00:00:00.000Z"),
    score: 3.0002830028533936
 },
  {
    title: 'The Oil Prince',
    released: ISODate("1966-01-01T00:00:00.000Z"),
    score: 3.0002830028533936
  }
]
```
