> 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: eg1, eg2, eg3
-->

# `range` (MongoDB Search Operator)

## Definition

The `range` operator supports querying and scoring numeric, date, and string values. You can use this operator to find results that are within a given numeric, date, objectId, or letter (from the English alphabet) range.

`range` supports querying the following data types:

- [number](https://www.mongodb.com/docs/search/indexes/field-types/number-type.md#std-label-bson-data-types-number), including `int32`, `int64`, and `double`

- [date](https://www.mongodb.com/docs/search/indexes/field-types/date-type.md#std-label-bson-data-types-date)

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

- [objectId](https://www.mongodb.com/docs/search/indexes/field-types/object-id-type.md#std-label-objectId-ref)

## Syntax

`range` has the following syntax:

```javascript
{
    "$search": {
       "index": <index name>, // optional, defaults to "default"
       "range": {
          "path": "<field-to-search>",
          "gt | gte": <value-to-search>,
          "lt | lte": <value-to-search>,
          "score": <score-options>,
          "doesNotAffect": "<facet-to-exclude>" | [<array-of-facets>]
       }
    }
}
```

## Options

`range` uses the following terms to construct a query:

| Field | Type | Description | Necessity |
| --- | --- | --- | --- |
| `gt` or `gte` | BSON date, number, or string, or objectId | Find values greater than (`>`) or greater than or equal to (`>=`) the given value. For number fields, the value can be an `int32`, `int64`, or `double` data type.; For date fields, the value must be an :ISODate formatted date.; For string fields, the value must be indexed as MongoDB Search `token` type.; For `ObjectId` fields, the value must be indexed as [objectId](https://www.mongodb.com/docs/search/indexes/field-types/object-id-type.md#std-label-objectId-ref) data type or [dynamic mappings](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-static-dynamic-mappings) must be set to `true`. | no |
| `lt` or `lte` | BSON date, number, or string, or objectId | Find values less than (`<`) or less than or equal to (`<=`) the given value. For number fields, the value can be an `int32`, `int64`, or `double` data type.; For date fields, the value must be an :ISODate formatted date.; For string fields, the value must be indexed as MongoDB Search `token` type.; For `ObjectId` fields, the value must be indexed as [objectId](https://www.mongodb.com/docs/search/indexes/field-types/object-id-type.md#std-label-objectId-ref) data type or [dynamic mappings](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-static-dynamic-mappings) must be set to `true`. | no |
| `path` | string or array of strings | Indexed field or fields to search. | yes |
| `score` | object | Modify the score assigned to matching search results. You can modify the default score using the following options: `boost`: multiply the result score by the given number.; `constant`: replace the result score with the given number.; `function`: replace the result score with the given expression. When querying array values, MongoDB Search assigns higher scores if more values in the array match the query. For information on using `score` in your query, see [Score the Documents in the Results.](https://www.mongodb.com/docs/search/query/score/overview.md#std-label-scoring-ref) | no |
| `doesNotAffect` | string or array of strings | Facet or list of facets to exclude from count recalculation on the basis of this query. Value must be one or more names of a facet defined in `$search.facets` or `$searchMeta.facets`. The operator uses the specified facets for filtering documents to match this query, but doesn't recalculate counts for them. For more information, see [Multi-Select Facets.](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-multi-select) | no |

## Examples

The following examples use the collection in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets). If you loaded the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) on your cluster, you can create the indexes using the index definitions in the examples below and run the example queries on your cluster.

### Number Example

The following examples use indexes on numeric fields in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) and run `range` queries against the indexed fields.

### Example 1

For this example, you can use either static or dynamic mappings to index the `runtime` field in the `sample_mflix.movies` collection. The query uses `gte` and `lte` fields to define the numeric range to search.

#### Sample Index

Use one of the following index definitions:

##### Dynamic Mapping Index Definition

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

##### Static Mapping Index Definition

The following index definition named `default` indexes the `runtime` field only in the `movies` collection.

```javascript
{
  "mappings": {
    "dynamic": false,
    "fields": {
      "runtime": {
        "type": "number"
      }
    }
  }
}
```

#### Sample Query

The following query searches for movies with a runtime greater than or equal to `2` and less than or equal to `3`. It includes a [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage to limit the output to `5` results and a [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to exclude all fields except `title` and `runtime`.

```json
db.movies.aggregate([
  {
    "$search": {
      "range": {
        "path": "runtime",
        "gte": 2,
        "lte": 3
      }
    }
  },
  {
    "$limit": 5
  },
  {
    "$project": {
      "_id": 0,
      "title": 1,
      "runtime": 1
    }
  }
])
```

**Output:**

```json
{ "runtime" : 3, "title" : "Dots" }
{ "runtime" : 3, "title" : "Sisyphus" }
{ "runtime" : 3, "title" : "The Fly" }
{ "runtime" : 2, "title" : "Andrè and Wally B." }
{ "runtime" : 2, "title" : "Luxo Jr." }
```

### Date Example

The following example uses the `range` operator to query a date field in the `sample_mflix.movies` collection. For this example, you can use either static or dynamic mappings to index the `date` type field named `released` in the collection.

#### Sample Index

Use one of the following index definitions:

##### Dynamic Mapping Index Definition

The following index definition named `default` indexes all the dynamically indexable fields in the `movies` collection, including the `released` field, which is of type `date`.

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

##### Static Mapping Index Definition

The following index definition named `default` indexes the `released` field in the `movies` collection:

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

#### Sample Query

The following query searches for movies released between January 1, 2010 and January 1, 2015. It includes a [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage to limit the output to 5 results and a [`$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`.

```javascript
db.movies.aggregate([
  {
    "$search": {
      "range": {
        "path": "released",
        "gt": ISODate("2010-01-01T00:00:00.000Z"),
        "lt": ISODate("2015-01-01T00:00:00.000Z")
      }
    }
  },
  {
    "$limit": 5
  },
  {
    "$project": {
      "_id": 0,
      "title": 1,
      "released": 1
    }
  }
])
```

**Output:**

```javascript
[
  {
    title: 'Too Much Johnson',
    released: ISODate('2014-08-30T00:00:00.000Z')
  },
  {
    title: 'Stolen Desire',
    released: ISODate('2012-07-01T00:00:00.000Z')
  },
  {
    title: 'The Monkey King',
    released: ISODate('2012-01-12T00:00:00.000Z')
  },
  { title: 'The Land', released: ISODate('2012-08-04T00:00:00.000Z') },
  {
    title: 'My Childhood',
    released: ISODate('2013-07-31T00:00:00.000Z')
  }
]
```

### ObjectId Example

The following example uses the `range` operator to query an `objectId` field in the `sample_mflix.movies` collection. For this example, you can use either static or dynamic mappings to index the `objectId` type field named `_id` in the collection.

#### Sample Index

Use one of the following index definitions:

##### Dynamic Mapping Index Definition

The following index definition named `default` indexes all the dynamically indexable fields in the `movies` collection, including the `_id` field, which is of type `objectId`.

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

##### Static Mapping Index Definition

The following index definition named `default` indexes the `_id` field in the `movies` collection:

```javascript
{
   "mappings": {
      "dynamic": false,
      "fields": {
         "_id": {
           "type": "objectId"
         }
      }
   }
}
```

#### Sample Query

The following example uses the `range` operator to query `_id` field for a range of `objectId` values in the `sample_mflix.movies` collection.

```javascript
db.movies.aggregate([
  {
    "$search": {
      "range": {
        "path": "_id",
        "gte": ObjectId("573a1396f29313caabce4a9a"),
        "lte": ObjectId('573a1396f29313caabce4ae7')
      }
    }
  },
  {
    "$project": {
      "_id": 1,
      "title": 1,
      "released": 1
    }
  }
])
```

**Output:**

```javascript
[
  {
    _id: ObjectId('573a1396f29313caabce4a9a'),
    title: 'The Godfather',
    released: ISODate('1972-03-24T00:00:00.000Z')
  },
  {
    _id: ObjectId('573a1396f29313caabce4a9b'),
    title: 'Get to Know Your Rabbit',
    released: ISODate('1972-06-01T00:00:00.000Z')
  },
  {
    _id: ObjectId('573a1396f29313caabce4aad'),
    title: 'The Tall Blond Man with One Black Shoe',
    released: ISODate('1973-08-30T00:00:00.000Z')
  },
  {
    _id: ObjectId('573a1396f29313caabce4abe'),
    title: 'The Great Northfield Minnesota Raid',
    released: ISODate('1972-05-12T00:00:00.000Z')
  },
  {
    _id: ObjectId('573a1396f29313caabce4ac4'),
    title: 'The Heartbreak Kid',
    released: ISODate('1973-02-01T00:00:00.000Z')
  },
  {
    _id: ObjectId('573a1396f29313caabce4ac7'),
    title: 'Gumshoe',
    released: ISODate('1971-12-01T00:00:00.000Z')
  },
  {
    _id: ObjectId('573a1396f29313caabce4ad9'),
    title: 'Heat',
    released: ISODate('1972-10-06T00:00:00.000Z')
  },
  {
    _id: ObjectId('573a1396f29313caabce4ae7'),
    title: 'Horror Express',
    released: ISODate('1973-12-01T00:00:00.000Z')
  }
]
```

### String Example

The following example uses the `range` operator to query a string field in the `sample_mflix.movies` collection. For this example, you must use static mappings to index the field named `title` in the collection as MongoDB Search `token` type.

#### Sample Index

The following index definition named `default` indexes the `title` field in the `movies`  collection as MongoDB Search `token` type:

```javascript
{
  "mappings": {
    "dynamic": false,
    "fields": {
      "title": {
        "type": "token",
        "normalizer": "lowercase"
      }
    }
  }
}
```

#### Sample Query

The following query searches for movie titles that contain characters between `city` and `country`. It includes a [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage to limit the output to 5 results and a [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to exclude all fields except `title`.

```json
db.movies.aggregate([
  {
    "$search": {
      "range": {
        "path": "title",
        "gt": "city",
        "lt": "country"
      }
    }
  },
  {
    "$limit": 5
  },
  {
    "$project": {
      "_id": 0,
      "title": 1
    }
  }
])
```

**Output:**

```json
[
  { title: 'Civilization' },
  { title: 'Clash of the Wolves' },
  { title: 'City Lights' },
  { title: 'Comradeship' },
  { title: 'Come and Get It' }
]
```

### Embedded Documents Example

The following query searches the `funding_rounds.raised_amount` field in the `sample_training.companies` collection for amount greater than or equal to `500000` and less than or equal to `1000000`. It uses the `returnStoredSource: true` and `returnScope` to retrieve and return the fields within the `funding_rounds` array of objects, which are stored on `mongot`. The query uses the sample index from the [Use Relative Path for Stored Source](https://www.mongodb.com/docs/search/indexes/field-types/embedded-documents-type.md#std-label-bson-data-types-embedded-documents) example.

➤ Try this in the [Search Playground](https://search-playground.mongodb.com/tools/code-sandbox/snapshots/68fbe4132ca0a88c52924bbb). The results in the MongoDB Search Playground might vary because the data in the MongoDB Search Playground is smaller than the sample collection used in the following example.

```json
db.companies.aggregate([
  {
    "$search": {
      "range": {
        "path": "funding_rounds.raised_amount",
        "gte": 500000,
        "lte": 1000000
      },
      "returnStoredSource": true,
      "returnScope": {
        "path": "funding_rounds"
      }
    }
  },
  {
    "$limit": 5
  }
])
```

**Output:**

```json
[
  {
    round_code: 'angel',
    raised_amount: 500000,
    raised_currency_code: 'USD'
  },
  {
    round_code: 'angel',
    raised_amount: 800000,
    raised_currency_code: 'USD'
  },
  {
    round_code: 'c',
    raised_amount: 1000000,
    raised_currency_code: 'USD'
  },
  {
    round_code: 'seed',
    raised_amount: 1000000,
    raised_currency_code: 'USD'
  },
  {
    round_code: 'a',
    raised_amount: 1000000,
    raised_currency_code: 'USD'
  }
]
```

### Metadata Example

The following query searches for movies with a runtime greater than or equal to `2` and less than or equal to `3`. The query uses the [`$searchMeta`](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta) stage to retrieve all movies in the following buckets (years) that match the search criteria:

- 1990, inclusive lower bound for this bucket

- 2000, exclusive upper bound for the 1990 bucket and inclusive lower bound for this bucket

- 2010, exclusive upper bound for the 2000 bucket and inclusive lower bound for this bucket

- 2020, exclusive upper bound for the 2010 bucket

The query uses an index named `default` that dynamically indexes all the fields in the `sample_mflix.movies` namespace.

```json
db.movies.aggregate([
  {
    "$searchMeta": {
      "facet": {
        "operator": {
          "range": {
            "path": "runtime",
            "gte": 2,
            "lte": 3
          }
        },
        "facets": {
          "yearFacet": {
            "type": "number",
            "path": "year",
            "boundaries": [1990, 2000, 2010, 2020 ]
          }
        }
      }
    }
  }
])
```

**Output:**

```javascript
[
  {
    count: { lowerBound: Long('15') },
    facet: {
      yearFacet: {
        buckets: [
          { _id: 1990, count: Long('2') },
          { _id: 2000, count: Long('3') },
          { _id: 2010, count: Long('5') }
        ]
      }
    }
  }
]
```
