span

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

<!-- Tab options on this page. Append to the .md URL to filter: ?tabs=<id,...> select specific tabs (e.g. ?tabs=nodejs,shell) ?allTabs=true include every tab (no param) default: one tab per tabset

Available tabs: other tabs: term-eg, or-eg -->

span (MongoDB Search Operator)

Definition

Note:

The span operator is deprecated. Instead, use the [phrase.](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref

The span operator finds text search matches within regions of a text field. You can use it to find strings which are near each other to specified degrees of precision. The span operator is more computationally intensive than other operators, because queries must keep track of positional information.

span is a term-level operator, which means that the query field is not analyzed. Term-level operators work well with the [Keyword Analyzer](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer because the query field is treated as a single term, with special characters included.

span queries aren't ranked by score.

Syntax

span has the following syntax:

{
   $search: {
     "index": <index name>, // optional, defaults to "default"
     "span": {
       "term" | <positional-operator>": {
         <operator-specification>
       }
     }
   }
}

Note:

span search queries can't use the [compound](https://www.mongodb.com/docs/search/query/operators-collectors/compound.md#std-label-compound-ref operator.

Term Operator

You can use the term operator to specify the terms to search. The term operator is required and when you use it with span [positional](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-positional-operators-ref operators, it must be the innermost child of the positional operators.

Syntax

The term operator has the following syntax:

"term": {
  "path": "<path-to-field>",
  "query": "<terms-to-search>"
}

Fields

The term operator takes the following fields:

Option Type Required? Description
path string yes Indexed field to search.
query string yes Term or phrase to search.

Positional Operators

You can use the positional operators to specify the position of the terms that you want to search with the [term](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-term-ref operator. The positional operators are of type document. You must specify at least one positional operator in your span operator query. The positional operators can take other span positional operators, recursively.

Note: About the Examples

The examples on this page use the sample_mflix.movies collection. If you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-sample-data and [create](https://www.mongodb.com/docs/search/indexes/manage-indexes.md#std-label-ref-create-index a [dynamic](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-static-dynamic-mappings index named default on the [movies collection](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix , you can run the following [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search sample queries against the collection. The sample queries use the [$limit](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit stage to limit the results to 5 documents and the [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to exclude all fields except the title field in the results.

span takes the following optional positional operators.

contains

The contains positional operator matches terms that are contained within other terms. You can use [positional operators](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-positional-operators-ref recursively or just the [term](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-term-ref operator within contains to specify the search terms.

Syntax

The contains positional operator has the following syntax:

{
  "$search": {
    "span": {
      "contains": {
        "spanToReturn": "inner"|"outer",
        "little": { <positional-or-term-operator-specification> },
        "big": { <positional-or-term-operator-specification> }
      }
    }
  }
}

Fields

The contains positional operator takes the following fields:

Fields Type Required? Description
big document yes One or more [positional operators](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-positional-operators-ref specified recursively or just the [term](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-term-ref operator. The type of query that span executes for big depends on the value of spanToReturn: outer: span matches terms from big that contain at least one term from little.; inner: span matches terms from little that are within terms from big.
little document yes One or more [positional operators](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-positional-operators-ref specified recursively or just the [term](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-term-ref operator. The type of query that span executes for little depends on the value of spanToReturn: inner: span matches terms from little that are within terms from big.; outer: span matches terms from big that contain at least one term from little.
score document no Score to apply to the results of this search.
spanToReturn string yes Type of query to execute and matching results to return. Value can be one of the following: inner - to execute a within query that matches terms from little that are inside of terms from big; outer - to execute a contains query that matches terms from big that contain at least one term from little

Example

The following example query uses span.contains to find documents in which the term train appears with the terms great and robbery, where great and robbery can be up to 5 positions apart in the title field.

db.movies.aggregate([
  {
    "$search": {
      "span": {
        "contains": {
          "spanToReturn": "outer",
          "little": {
            "term": {
              "path": "title",
              "query": "train"
            }
          },
          "big": {
            "near": {
              "clauses": [
                {
                  "term": {
                    "path": "title",
                    "query": "great"
                  }
                },
                {
                  "term": {
                    "path": "title",
                    "query": "robbery"
                  }
                }
              ],
              "slop": 5
            }
          }
        }
      }
    }
  },
  {
    "$limit": 5
  },
  {
    "$project": {
      "_id": 0,
      "title": 1
    }
  }
])

Output:

[
  { title: 'The Great Train Robbery' },
  { title: 'The Great Train Robbery' },
  { title: "The Great St. Trinian's Train Robbery" }
]

MongoDB Search returns documents that contain the term train (specified using little) inside the terms great and robbery (specified using big). If you set spanToReturn on line 6 to inner, MongoDB Search returns the same documents because the term train (specified using little) appears within the terms great and robbery (specified using big).

first

The first positional operator identifies the position of the search term by using a specified number. You can specify the search terms using [positional operators](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-positional-operators-ref recursively, or just the [term](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-term-ref operator. span matches documents where the position of the search term is less than or equal to the specified number.

Syntax

The first positional operator has the following syntax:

{
  "$search": {
    "span": {
      "first": {
        "endPositionLte": <term-position>,
        "operator": { <span-positional-or-term-operator-specification> },
        "score": { <score-options> }
      }
    }
  }
}

Fields

The first positional operator takes the following fields:

Option Type Required? Description
endPositionLte int no Number that specifies the position of the search term. If you specify a search for multiple terms, the last term should be less than or equal to this value. If omitted, defaults to 3.
operator document yes Document that contains the [positional operators](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-positional-operators-ref or [term](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-term-ref operator options.
score document no Score to apply to the results of this search.

Example

The following example queries use span.first to find documents in which the specified string appears in the title field. The endPositionLte parameter has a value of 2, which means that the search term specified using the term operator must be the first or second word in the field.

term Example

db.movies.aggregate([
  {
    "$search": {
      "span": {
        "first": {
          "endPositionLte": 2,
          "operator": {
            "term": {
              "path": "title",
              "query": "dance"
            }
          }
        }
      }
    }
  },
  {
    "$limit": 5
  },
  {
    "$project": {
      "_id": 0,
      "title": 1
    }
  }
])

Output:

[
  { title: 'Dance Program' },
  { title: 'Slam Dance' },
  { title: 'Last Dance' },
  { title: 'War Dance' },
  { title: 'Delhi Dance' }
]

MongoDB Search returns the documents that contain search word dance in the first or second position of the title field.

near

The near positional operator matches two or more clauses that contain the search term near each other. You can specify the search terms using a list of [positional operators](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-positional-operators-ref recursively or just the [term](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-term-ref operator.

Syntax

The near positional operator has the following syntax:

{
  "$search": {
    "span": {
      "near": {
        "clauses": [
          { <span-positional-or-term-operator-specification> },
          ...
        ],
        "slop": <distance-number>,
        "inOrder": true|false
      }
    }
  }
}

Fields

The near positional operator takes the following fields:

Field Type Required? Description
clauses array of documents yes Span clauses that must be near one another. Clauses can't be empty. Each document contains span [positional](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-positional-operators-ref or just the [term](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-term-ref operator options.
inOrder boolean no Flag that specifies whether the search for terms in the clauses must be in the order specified and must not be overlapping. Value can be one of the following: true - to search for terms in the clauses in the specified order specified, without overlapping; false - to search for terms in the clauses in any order If omitted, defaults to false.
score document no Score to apply to the results of this search.
slop integer no Allowable distance between terms in the clauses. Lower values allow less positional distance between the terms and greater values allow more distance between the words to satisfy the query. The default is 0, which means that words in the different clauses must be adjacent to be considered a match.

Example

The following example query uses span.near to search for documents in which the strings prince and pauper are found near each other. The inOrder parameter is set to false, so the search terms can be in any order. The slop parameter is set to 4, so the search terms can be separated by up to only 4 words.

db.movies.aggregate([
  {
    "$search" : {
      "span": {
        "near": {
          "clauses": [
            { "term": { "path": "title", "query": "prince" } },
            { "term": { "path": "title", "query": "pauper" } }
          ],
          "slop": 4,
          "inOrder": false
        }
      }
    }
  },
  {
    "$limit": 5
  },
  {
    "$project": {
      "_id": 0,
      "title": 1
    }
  }
])

Output:

[ { title: 'The Prince and the Pauper' } ]

MongoDB Search returns a document that contain search words prince and pauper, separated by less than four words, in the title field.

or

The or positional operator matches any of two or more clauses. You can specify the search terms using a list of [positional operators](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-positional-operators-ref recursively or just the [term](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-term-ref operator.

Syntax

The or positional operator has the following syntax:

{
  "$search": {
    "span": {
      "or": {
        "clauses": [
          { <span-positional-or-term-operator-specification> },
          ...
        ],
        "score": { <scoring-options> }
      }
    }
  }
}

Fields

The or positional operator takes the following fields:

Option Type Required? Description
clauses array of documents yes Span clauses that specify the search terms. One of the clauses must match, and clauses can't be empty. Each document must contain span [positional operators](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-positional-operators-ref specified recursively or just the [term](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-term-ref operator options.
score document no Score to apply to the results of this search.

Example

The following example query uses span.or clauses to specify two [term](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-term-ref operator queries that search for documents in which the title field has either city or country.

db.movies.aggregate([
  {
    "$search" : {
      "span": {
        "or": {
          "clauses": [
            { "term": { "path": "title", "query": "city" } },
            { "term": { "path": "title", "query": "country" } }
          ],
        }
      }
    }
  },
  {
    "$limit": 5
  },
  {
    "$project": {
      "_id": 0,
      "title": 1
    }
  }
])

Output:

[
  { title: 'Country' },
  { title: 'City Lights' },
  { title: 'King & Country' },
  { title: 'Fat City' },
  { title: 'Atlantic City' }
]

MongoDB Search returns the documents that contain the search words city or country in the title field, but not both in the same title.

subtract

The subtract positional operator removes matches that overlap with another match. You can specify the search terms using a list of [positional operators](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-positional-operators-ref recursively or just the [term](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-term-ref operator. The subtract clause can be used to exclude certain strings from your search results.

Syntax

The subtract positional operator has the following syntax:

{
  "$search": {
    "span": {
      "subtract": {
        "include": { <span-positional-or-term-operator-specification> },
        "exclude": { <span-positional-or-term-operator-specification> }
      }
    }
  }
}

Fields

The subtract positional operator takes the following fields:

Option Type Required? Description
exclude document yes Document that specifies the term or phrase matches to remove that overlap with the term or phrase matches specified in the include field. You can specify the term or phrase using any span [positional operators](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-positional-operators-ref and the [term](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-term-ref operator.
include document yes Document that specifies the term matches to include using any [positional operators](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-positional-operators-ref or just the [term](https://www.mongodb.com/docs/search/query/operators-collectors/span.md#std-label-span-term-ref operator.
score document no Score to apply to the results of this search.

Example

The following example query uses span.subtract to search for documents in which the title field contains the words father and son, in any order, within 3 words of each other. It excludes any document in which the word like occurs between father and son.

db.movies.aggregate([
  {
    "$search" : {
      "span": {
        "subtract": {
          "include": {
            "near": {
              "clauses": [
                { "term": { "path": "title", "query": "father" } },
                { "term": { "path": "title", "query": "son" } }
              ],
              "inOrder": false,
              "slop": 3
            }
          },
          "exclude": { "term": { "path": "title", "query": "like" } }
        }
      }
    }
  },
  {
    "$limit": 5
  },
  {
    "$project": {
      "_id": 0,
      "title": 1
    }
  }
])

Output:

[
  { title: 'Father, Son & Holy Cow' },
  { title: 'My Father and My Son' },
  { title: 'Jimmy Rosenberg: The Father, the Son & the Talent' }
]

MongoDB Search doesn't return the document with the title Like Father Like Son because although the title field includes the words father and son, it also has like between them, which is in the exclude criteria of the query.