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

# `$search`

The [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage performs a full-text search on the specified field or fields. The field or fields must be covered by an MongoDB Search [index.](https://www.mongodb.com/docs/search/indexes/index-definitions.md#std-label-ref-index-definitions)

## Compatibility

The `$search` stage is available in the following environments:

- [MongoDB Atlas](https://www.mongodb.com/docs/atlas/)

- [MongoDB Enterprise](https://www.mongodb.com/docs/manual/administration/install-enterprise.md#std-label-install-mdb-enterprise) deployments running version 8.2 or later with the [Kubernetes Operator.](https://www.mongodb.com/docs/kubernetes/current.md#std-label-k8s-operator)

- [MongoDB Community](https://www.mongodb.com/docs/manual/administration/install-community.md#std-label-install-mdb-community-edition) deployments running version 8.2 or later

## Syntax

A `$search` pipeline stage has the following prototype form:

```json
{
  $search: {
    "index": "<index-name>",
    "<operator-name>"|"<collector-name>": {
      <operator-specification>|<collector-specification>
    },
    "highlight": {
      <highlight-options>
    },
    "concurrent": true | false,
    "count": {
      <count-options>
    },
    "searchAfter"|"searchBefore": "<encoded-token>",
    "scoreDetails": true| false,
    "sort": {
      <fields-to-sort>: 1 | -1
    },
    "returnScope": {
      "path": "<embedded-documents-field-to-retrieve>"
    },
    "returnStoredSource": true | false,
    "searchNodePreference": {
      "key": <preference-string>
    }
  }
}
```

## Fields

The `$search` stage takes a document with the following fields:

| Field | Type | Necessity | Description |
| --- | --- | --- | --- |
| `<collector-name>` | object | Conditional | Name of the [collector](https://www.mongodb.com/docs/search/query/operators-collectors/overview.md#std-label-collectors-ref) to use with the query. You can provide a document that contains the collector-specific options as the value for this field. Either this or `<operator-name>` is required. |
| `concurrent` | boolean | Optional | Parallelize search across segments on [dedicated search nodes](https://www.mongodb.com/docs/search/deployment/deployment-options.md#std-label-what-is-search-node). If you don't have separate search nodes on your cluster, MongoDB Search ignores this flag. If omitted, defaults to `false`. To learn more, see [Parallelize Query Execution Across Segments.](https://www.mongodb.com/docs/search/query/concurrent-query.md#std-label-concurrent-ref) |
| `count` | object | Optional | Document that specifies the [count](https://www.mongodb.com/docs/search/query/counting.md#std-label-count-ref) options for retrieving a count of the results. To learn more, see [Count MongoDB Search Results.](https://www.mongodb.com/docs/search/query/counting.md#std-label-count-ref) |
| `highlight` | object | Optional | Document that specifies the [highlighting](https://www.mongodb.com/docs/search/query/highlighting.md#std-label-highlight-ref) options for displaying search terms in their original context. |
| `index` | string | Optional | Name of the MongoDB Search index to use. If omitted, defaults to `default`. If you name your index `default`, you don't need to specify an `index` parameter in the [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) pipeline stage. If you give a custom name to your index, you must specify this name in the `index` parameter. MongoDB Search doesn't return results if you misspell the index name or if the specified index doesn't already exist on the cluster. |
| `<operator-name>` | object | Conditional | Name of the [operator](https://www.mongodb.com/docs/search/query/operators-collectors/overview.md#std-label-operators-ref) to search with. You can provide a document that contains the operator-specific options as the value for this field. Either this or `<collector-name>` is required. Use the [compound](https://www.mongodb.com/docs/search/query/operators-collectors/compound.md#std-label-compound-ref) operator to run a compound query with multiple operators. |
| `returnScope` | Object | Optional | Object that sets the context of the query to the specified embedded document field. You must also specify `returnStoredSource` and set it to `true`. |
| `returnStoredSource` | boolean | Conditional | Flag that specifies whether to perform a full document lookup on the backend database or return only stored source fields directly from MongoDB Search. If omitted, defaults to `false`. Must be `true` if you specify `returnScope`. To learn more, see [Return Stored Source Fields.](https://www.mongodb.com/docs/search/query/return-stored-source.md#std-label-fts-return-stored-source-option) |
| `searchAfter` | string | Optional | Reference point for retrieving results. `searchAfter` returns documents starting immediately following the specified reference point. The reference point must be a Base64-encoded token generated by the [`$meta`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#mongodb-expression-exp.-meta) keyword `searchSequenceToken`. To learn more, see [Paginate the Results](https://www.mongodb.com/docs/search/query/paginate-results.md#std-label-fts-paginate-results). This field is mutually exclusive with the `searchBefore` field. |
| `searchBefore` | string | Optional | Reference point for retrieving results. `searchBefore` returns documents starting immediately before the specified reference point. The reference point must be a Base64-encoded token generated by the [`$meta`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#mongodb-expression-exp.-meta) keyword `searchSequenceToken`. To learn more, see [Paginate the Results](https://www.mongodb.com/docs/search/query/paginate-results.md#std-label-fts-paginate-results). This field is mutually exclusive with the `searchAfter` field. |
| `searchNodePreference` | object | Optional | Document that enables preferential routing for this query. If you set a value for this field, Atlas executes this query against the same search node each time as long as that value remains the same, overriding the [default query routing](https://www.mongodb.com/docs/search/query/query-ref.md#std-label-about-mongot) behavior. This document contains a key-value pair where the value of `key` is an arbitrary string. IMPORTANT: Enabling this setting can improve the consistency of your search results, but doesn't guarantee perpetual consistency. Changes to your data set, index structure, cluster topology, or preferred node availability might still cause inconsistencies. |
| `scoreDetails` | boolean | Optional | Flag that specifies whether to retrieve a detailed breakdown of the score for the documents in the results. If omitted, defaults to `false`. To view the details, you must use the [`$meta`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/meta.md#mongodb-expression-exp.-meta) expression in the [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage. To learn more, see [Return the Score Details.](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-score-details) |
| `sort` | object | Optional | Document that specifies the fields to sort the MongoDB Search results by in ascending or descending order. You can sort by date, number (integer, float, and double values), and string values. To learn more, see [Sort MongoDB Search Results.](https://www.mongodb.com/docs/search/query/sort.md#std-label-sort-ref) |

## Behavior

[`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) must be the first stage of any pipeline it appears in. [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) cannot be used in:

- a [view definition](https://www.mongodb.com/docs/manual/core/views.md#std-label-views-landing-page)

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

## Aggregation Variable

[`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) returns only the results of your query. The metadata results of your [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) query are saved in the `$$SEARCH_META` aggregation variable. You can use the `$$SEARCH_META` variable to view the metadata results for your [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) query.

The `$$SEARCH_META` aggregation variable can be used anywhere after a [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage in any pipeline, but it can't be used after the [`$lookup`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup.md#mongodb-pipeline-pipe.-lookup) or [`$unionWith`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionWith.md#mongodb-pipeline-pipe.-unionWith) stage in any pipeline. The `$$SEARCH_META` aggregation variable can't be used in any subsequent stage after a [`$searchMeta`](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta) stage.

**Example:**

Suppose the following index on the `sample_mflix.movies` collection.

```json
{
  "mappings": {
    "dynamic": false,
    "fields": {
      "released": {
        "type": "date"
      }
    }
  }
}
```

The following query searches for movies released near September 01, 2011 using the [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage. The query includes a:

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

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

  - `docs` field with an array of the top `5` search results

  - `meta` field with the value of `$$SEARCH_META` variable

```json
db.movies.aggregate([
  {
    "$search": {
      "near": {
        "path": "released",
        "origin": ISODate("2011-09-01T00:00:00.000+00:00"),
        "pivot": 7776000000
      }
    }
  },
  {
    $project: {
      "_id": 0,
      "title": 1,
      "released": 1
    }
  },
  { "$limit": 5 },
  {
    "$facet": {
      "docs": [],
      "meta": [
        {"$replaceWith": "$$SEARCH_META"},
        {"$limit": 1}
      ]
    }
  }
])
```

**Output:**

```json
{
  "docs" : [
    {
      "title" : "Submarino",
      "released" : ISODate("2011-09-01T00:00:00Z")
    },
    {
      "title" : "Devil's Playground",
      "released" : ISODate("2011-09-01T00:00:00Z")
    },
    {
      "title" : "Bag It",
      "released" : ISODate("2011-09-01T00:00:00Z")
    },
    {
      "title" : "Dos",
      "released" : ISODate("2011-09-01T00:00:00Z")
    },
    {
      "title" : "We Were Here",
      "released" : ISODate("2011-09-01T00:00:00Z")
    }
  ],
  "meta" : [
    { "count" : { "lowerBound" : NumberLong(17373) } }
  ]
}
```

To learn more about the `$$SEARCH_META` variable and its usage, see:

- [facet](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-aggregation-variable)

- [count](https://www.mongodb.com/docs/search/query/counting.md#std-label-fts-count-aggregation-variable)

## Troubleshooting

If you are experiencing issues with your MongoDB Search [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) queries, see [Troubleshoot Queries.](https://www.mongodb.com/docs/search/query/query-ref.md#std-label-fts-troubleshooting)
