For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

How to Index String Fields

Use the MongoDB Search string type to index string fields. Use the MongoDB Search phrase, querystring, span, text, wildcard, regex, and moreLikeThis operators to query fields indexed as the string type.

The string type doesn't support all MongoDB Search features for string fields. Index the string field as a token to:

  • Run a facet query on string fields.

  • Sort the MongoDB Search results by string fields.

  • Find an exact match for queries using equals, in, and range operators.

The MongoDB Search dynamic mappings with the default typeSet only indexes string fields as string types. Specify a custom typeSet to dynamically index strings as token or autocomplete to use their supported features.

Important

MongoDB Search won't index string fields where analyzer tokens exceed 32766 bytes in size. If using the keyword analyzer, string fields which exceed 32766 bytes will not be indexed.

1

Use your service account to generate an access token, which authenticates your requests to the Atlas Administration API. To learn how to generate an access token, see Make an API (Application Programming Interface) Request.

2

Replace the following values in the curl command below. This command sends a POST request to your cluster to create a MongoDB Search index with the string field type.

  • Replace {ACCESS-TOKEN} with the output from the preceding step

  • Replace {groupId} with the project ID of the project where you want to create the MongoDB Search index

  • Replace {clusterName} with the name of the cluster where you want to create the MongoDB Search index

1curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
2 --header "Accept: application/vnd.atlas.2025-03-12+json" \
3 --header "Content-Type: application/json" \
4 -X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
5 -d '{ "collectionName": "<collection>",
6 "database": "<database>",
7 "name": "default",
8 "type": "search",
9 "definition": {
10 "mappings": {
11 "dynamic": true|false,
12 "fields": {
13 "<field-name>": {
14 "type": "string",
15 "analyzer": "<atlas-search-analyzer>",
16 "searchAnalyzer": "<atlas-search-analyzer>",
17 "indexOptions": "docs|freqs|positions|offsets",
18 "store": true|false,
19 "ignoreAbove": <integer>,
20 "similarity": { "type": "bm25|boolean|stableTfl" },
21 "multi": {<string-field-definition>},
22 "norms": "include|omit"
23 }
24 }
25 }
26 }
27 }'

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
2 --header "Accept: application/vnd.atlas.2025-03-12+json" \
3 --header "Content-Type: application/json" \
4 -X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
5 -d '{ "collectionName": "movies",
6 "database": "sample_mflix",
7 "name": "default",
8 "type": "search",
9 "definition": {
10 "mappings": {
11 "dynamic": false,
12 "fields": {
13 "title": {
14 "type": "string"
15 }
16 }
17 }
18 }
19 }'
{"collectionName":"movies","database":"sample_mflix","indexID":"<indexID>","latestDefinition":{"mappings":{"dynamic":true,"fields":{"title":{"type":"string"}}}},"latestDefinitionVersion":{"version":0},"name":"default","queryable":false,"status":"PENDING","type":"search"}
1
search-index.json
1{
2 "name": "default",
3 "collectionName": "<collection>",
4 "database": "<database>",
5 "definition": {
6 "mappings": {
7 "dynamic": true|false,
8 "fields": {
9 "<field-name>": {
10 "type": "string",
11 "analyzer": "<atlas-search-analyzer>",
12 "searchAnalyzer": "<atlas-search-analyzer>",
13 "indexOptions": "docs|freqs|positions|offsets",
14 "store": true|false,
15 "ignoreAbove": <integer>,
16 "similarity": { "type": "bm25|boolean|stableTfl" },
17 "multi": { <string-field-definition> },
18 "norms": "include|omit"
19 }
20 }
21 }
22 }
23 }
24}
2

In your terminal, connect to your cluster from the Atlas CLI. To learn more, see Connect from the Atlas CLI.

3

Run the atlas clusters search indexes create command in your terminal, replacing <clusterName> with the name of the cluster, and <path-to-file> with the path to the search-index.json file:

atlas clusters search indexes create --clusterName <cluster-name> --file <path-to-file>

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1{
2 "name": "default",
3 "collectionName": "movies",
4 "database": "sample_mflix",
5 "definition": {
6 "mappings": {
7 "dynamic": false,
8 "fields": {
9 "title": {
10 "type": "string"
11 }
12 }
13 }
14 }
15}
1

Open Compass and connect to your cluster. For detailed instructions, see Connect to a Cluster via Compass.

2

On the Database screen, click the name of the database, then click the name of the collection.

3
  1. Click the Indexes tab, then select Search Indexes.

  2. Click Create Atlas Search Index to open the index creation dialog box.

  3. Specify a name for the index.

    Your MongoDB Search index is named default by default. If you keep this name, then your index will be the default Search index for any MongoDB Search query that does not specify a different index option in its operators. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.

  4. Specify the JSON MongoDB Search index definition.

    1{
    2 "mappings": {
    3 "dynamic": true|false,
    4 "fields": {
    5 "<field-name>": {
    6 "type": "string",
    7 "analyzer": "<atlas-search-analyzer>",
    8 "searchAnalyzer": "<atlas-search-analyzer>",
    9 "indexOptions": "docs|freqs|positions|offsets",
    10 "store": true|false,
    11 "ignoreAbove": <integer>,
    12 "similarity": { "type": "bm25|boolean|stableTfl" },
    13 "multi": { <string-field-definition> },
    14 "norms": "include|omit"
    15 }
    16 }
    17 }
    18}
  5. Click Create Search Index.

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1{
2 "mappings": {
3 "dynamic": false,
4 "fields": {
5 "title": {
6 "type": "string"
7 }
8 }
9 }
10}
1

In your terminal, connect to your Atlas cloud-hosted deployment or local deployment from mongosh. For detailed instructions on how to connect, see Connect to a Deployment.

2
use <database>
switched to db <database>
3
db.<collection>.createSearchIndex(
"default",
{
"mappings": {
"dynamic": true|false,
"fields": {
"<field-name>": {
"type": "string"
"analyzer": "<atlas-search-analyzer>",
"searchAnalyzer": "<atlas-search-analyzer>",
"indexOptions": "docs|freqs|positions|offsets",
"store": true|false,
"ignoreAbove": <integer>,
"similarity": { "type": "bm25|boolean|stableTfl" }
"multi": { <string-field-definition> },
"norms": "include|omit"
},
}
}
}
)
default

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1db.movies.createSearchIndex(
2 {
3 "mappings": {
4 "dynamic": false,
5 "fields": {
6 "title": {
7 "type": "string"
8 }
9 }
10 }
11 }
12)

Choose your preferred configuration method in the Atlas UI and then select the database and collection.

  1. Click Refine Your Index to configure your index.

  2. In the Field Mappings section, click Add Field Mapping to open the Add Field Mapping window.

  3. Click Customized Configuration.

  4. Select the field to index from the Field Name dropdown.

    Note

    You can't index fields that contain the dollar ($) sign at the start of the field name.

  5. Click the Data Type dropdown and select String.

  6. Configure the field properties for the string type. To learn more, see Field Properties.

  7. Click Add.

Note

To configure the similarity.type property for string fields, use the JSON Editor.

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use the Visual Editor or JSON Editor to configure these indexes. After you select your preferred configuration method, select the database and collection, and refine your index to add field mappings.

1

In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project for this project:

1# Create a new directory for the project
2mkdir atlas-search-project && cd atlas-search-project

Add the C driver to your project by following the instructions in the MongoDB C Driver documentation.

2

Create a create_index.c file in your project directory, and copy and paste the following code into the file.

create_index.c
1#include <mongoc/mongoc.h>
2#include <stdlib.h>
3
4int main (void)
5{
6 mongoc_client_t *client = NULL;
7 mongoc_collection_t *collection = NULL;
8 mongoc_database_t *database = NULL;
9 bson_error_t error;
10 bson_t cmd = BSON_INITIALIZER;
11 bool ok = true;
12
13 mongoc_init();
14
15 // Connect to your Atlas deployment
16 client = mongoc_client_new("<connectionString>");
17 if (!client) {
18 fprintf(stderr, "Failed to create a MongoDB client.\n");
19 ok = false;
20 goto cleanup;
21 }
22
23 // Access your database and collection
24 database = mongoc_client_get_database(client, "<databaseName>");
25 collection = mongoc_database_get_collection(database, "<collectionName>");
26
27 // Specify the command and the new index
28 const char *cmd_str = BSON_STR({
29 "createSearchIndexes" : "<collectionName>",
30 "indexes" : [ {
31 "name" : "default",
32 "definition" : {
33 "mappings": {
34 "dynamic": true|false,
35 "fields": {
36 "<fieldName>" : {
37 "type": "string"
38 "analyzer": "<atlas-search-analyzer>",
39 "searchAnalyzer": "<atlas-search-analyzer>",
40 "indexOptions": "docs|freqs|positions|offsets",
41 "store": true|false,
42 "ignoreAbove": <integer>,
43 "similarity": { "type": "bm25|boolean|stableTfl" },
44 "multi": { <string-field-definition> },
45 "norms": "include|omit"
46 }
47 },
48 },
49 }
50 } ]
51 });
52
53 // Convert your command to BSON
54 if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) {
55 fprintf(stderr, "Failed to parse command: %s\n", error.message);
56 ok = false;
57 goto cleanup;
58 }
59
60 // Create the MongoDB Search index by running the command
61 if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) {
62 fprintf(stderr, "Failed to run createSearchIndexes: %s\n", error.message);
63 ok = false;
64 goto cleanup;
65 }
66 printf ("Index created!\n");
67
68cleanup:
69 mongoc_collection_destroy (collection);
70 mongoc_client_destroy (client);
71 mongoc_database_destroy (database);
72 bson_destroy (&cmd);
73 mongoc_cleanup ();
74 return ok ? EXIT_SUCCESS : EXIT_FAILURE;
75}

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.

Note

For a local or self-managed deployment, your connection string should use the following format:

mongodb://localhost:<port-number>/?directConnection=true

To learn more, see Connection Strings.

3

To configure your application, create a CMakeLists.txt file in your project directory. Then, add the following code to the file:

CMakeLists.txt
1cmake_minimum_required(VERSION 3.11)
2project(atlas-search-index LANGUAGES C)
3add_executable (index.out create_index.c)
4find_package(mongoc <version> REQUIRED)
5target_link_libraries(index.out mongoc::mongoc)

The preceding code performs the following actions:

  • Configures a C project.

  • Creates a index.out executable for your application.

  • Finds and requires the C driver. Replace the <version> placeholder with your C driver version number, such as 2.0.0.

  • Links the program to the libmongoc library.

Note

In the sample CMakeLists.txt file, the mongoc::mongoc target points to either the static library or the shared library. The library type depends on which one is available and whichever type the user specifies in the MONGOC_DEFAULT_IMPORTED_LIBRARY_TYPE CMake configuration setting. If you don't set this value and both library types are available, mongoc::mongoc uses the static library.

You can use the mongoc::static target to explicitly use the static library or the mongoc::shared target to use the shared library.

4

In your terminal, run the following commands to build and run this application:

cmake -S. -Bcmake-build
cmake --build cmake-build --target index.out
./cmake-build/index.out
Index created!

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1#include <mongoc/mongoc.h>
2#include <stdlib.h>
3
4int main (void)
5{
6 mongoc_client_t *client = NULL;
7 mongoc_collection_t *collection = NULL;
8 mongoc_database_t *database = NULL;
9 bson_error_t error;
10 bson_t cmd = BSON_INITIALIZER;
11 bool ok = true;
12
13 mongoc_init();
14
15 // Connect to your Atlas deployment
16 client = mongoc_client_new("<connectionString>");
17 if (!client) {
18 fprintf(stderr, "Failed to create a MongoDB client.\n");
19 ok = false;
20 goto cleanup;
21 }
22
23 // Access your database and collection
24 database = mongoc_client_get_database(client, "sample_mflix");
25 collection = mongoc_database_get_collection(database, "movies");
26
27 // Specify the command and the new index
28 const char *cmd_str = BSON_STR({
29 "createSearchIndexes" : "movies",
30 "indexes" : [ {
31 "name" : "default",
32 "definition" : {
33 "mappings": {
34 "dynamic": false,
35 "fields": {
36 "title" : {
37 "type": "string"
38 }
39 }
40 },
41 }
42 } ]
43 });
44
45 // Convert your command to BSON
46 if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) {
47 fprintf(stderr, "Failed to parse command: %s\n", error.message);
48 ok = false;
49 goto cleanup;
50 }
51
52 // Create the MongoDB Search index by running the command
53 if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) {
54 fprintf(stderr, "Failed to run createSearchIndexes: %s\n", error.message);
55 ok = false;
56 goto cleanup;
57 }
58 printf ("Index created!\n");
59
60cleanup:
61 mongoc_collection_destroy (collection);
62 mongoc_client_destroy (client);
63 mongoc_database_destroy (database);
64 bson_destroy (&cmd);
65 mongoc_cleanup ();
66 return ok ? EXIT_SUCCESS : EXIT_FAILURE;
67}
1

In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project for this project:

# Create a new directory for the project
mkdir atlas-search-project && cd atlas-search-project

For more detailed installation instructions, see the MongoDB C++ Driver documentation.

2

Create a CreateIndex.cpp file in your project directory, and copy and paste the following code into the file.

CreateIndex.cpp
1#include <iostream>
2
3#include <bsoncxx/builder/basic/document.hpp>
4#include <bsoncxx/json.hpp>
5#include <mongocxx/client.hpp>
6#include <mongocxx/instance.hpp>
7#include <mongocxx/uri.hpp>
8
9using bsoncxx::builder::basic::kvp;
10using bsoncxx::builder::basic::make_document;
11
12
13int main(){
14
15 mongocxx::instance instance;
16 mongocxx::uri uri("<connection string>");
17 mongocxx::client client(uri);
18
19 auto db = client["<database>"];
20 auto collection = db["<collection>"];
21
22 // instantiate a ``mongocxx::search_index_view`` on your collection
23 auto siv = collection.search_indexes();
24
25 {
26 auto name = "default";
27 auto definition = make_document(
28 kvp("mappings", make_document(
29 kvp("dynamic", true|false),
30 kvp("fields", make_document(
31 kvp("<field-name>", make_document(
32 kvp("type", "string"),
33 kvp("analyzer", "<analyzer-name>"),
34 kvp("searchAnalyzer", "<search-analyzer-name>"),
35 kvp("indexOptions", "docs|freqs|positions|offsets"),
36 kvp("store", true|false),
37 kvp("ignoreAbove", <integer>),
38 kvp("similarity", make_document( kvp("type", "bm25|boolean|stableTfl"))),
39 kvp("multi", make_document( <string-field-definition> )),
40 kvp("norms", "include|omit")
41 ))
42 ))
43 ))
44 );
45
46 auto model = mongocxx::search_index_model(name, definition.view());
47
48 // Create the search index
49 auto result = siv.create_one(model);
50 std::cout << "New index name: " << result << std::endl;
51 }
52}

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.

Note

For a local or self-managed deployment, your connection string should use the following format:

mongodb://localhost:<port-number>/?directConnection=true

To learn more, see Connection Strings.

3
c++ --std=c++17 CreateIndex.cpp $(pkg-config --cflags --libs libmongocxx) -o ./app.out
./app.out
New index name: default

Tip

MacOS Error

MacOS users might see the following error after running the preceding commands:

dyld[54430]: Library not loaded: @rpath/libmongocxx._noabi.dylib

To resolve this error, use the -Wl,-rpath linker option to set the @rpath, as shown in the following code:

c++ --std=c++17 CreateIndex.cpp -Wl,-rpath,/usr/local/lib/ $(pkg-config --cflags --libs libmongocxx) -o ./app.out
./app.out

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1#include <iostream>
2
3#include <bsoncxx/builder/basic/document.hpp>
4#include <bsoncxx/json.hpp>
5#include <mongocxx/client.hpp>
6#include <mongocxx/instance.hpp>
7#include <mongocxx/uri.hpp>
8
9using bsoncxx::builder::basic::kvp;
10using bsoncxx::builder::basic::make_document;
11
12
13int main(){
14
15 mongocxx::instance instance;
16 mongocxx::uri uri("<connection string>");
17 mongocxx::client client(uri);
18
19 auto db = client["sample_mflix"];
20 auto collection = db["movies"];
21
22 // instantiate a ``mongocxx::search_index_view`` on your collection
23 auto siv = collection.search_indexes();
24
25 {
26 auto name = "default";
27 auto definition = make_document(
28 kvp("mappings", make_document(
29 kvp("dynamic", false),
30 kvp("fields", make_document(
31 kvp("title", make_document(
32 kvp("type", "string")
33 ))
34 ))
35 ))
36 );
37
38 auto model = mongocxx::search_index_model(name, definition.view());
39
40 // Create the search index
41 auto result = siv.create_one(model);
42 std::cout << "New index name: " << result << std::endl;
43 }
44}
1

In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project and initialize your project in that directory:

# Create a new directory and initialize the project
mkdir atlas-search-project && cd atlas-search-project
dotnet new console
# Add the MongoDB .NET/C# Driver to your project
dotnet add package MongoDB.Driver

For more detailed installation instructions, see the MongoDB .NET/C# Driver documentation.

2

Paste the following code into the Program.cs file.

Program.cs
1using MongoDB.Bson;
2using MongoDB.Driver;
3
4// connect to your Atlas deployment
5var uri = "<connection-string>";
6
7var client = new MongoClient(uri);
8
9var db = client.GetDatabase("<database>");
10var collection = db.GetCollection<BsonDocument>("<collection>");
11
12// define your MongoDB Search index
13var index = new CreateSearchIndexModel(
14 "default", new BsonDocument
15 {
16 { "mappings", new BsonDocument
17 {
18 { "dynamic", true|false },
19 { "fields", new BsonDocument
20 {
21 { "<field-name>", new BsonDocument
22 {
23 { "type", "string" },
24 { "analyzer", "<analyzer-name>"},
25 { "searchAnalyzer", "<search-analyzer-name>"},
26 { "indexOptions", "docs|freqs|positions|offsets"},
27 { "store", true|false },
28 { "ignoreAbove", <integer> },
29 { "similarity", new BsonDocument { { "type", "bm25|boolean|stableTfl" } } },
30 { "multi", new BsonDocument { <string-field-definition> },
31 { "norms", "include|omit" }
32 }
33 }
34 }
35 }
36 }
37 }
38 });
39
40var result = collection.SearchIndexes.CreateOne(index);
41Console.WriteLine($"New index name: {result}");

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.

Note

For a local or self-managed deployment, your connection string should use the following format:

mongodb://localhost:<port-number>/?directConnection=true

To learn more, see Connection Strings.

3
dotnet run Program.cs
New index name: default

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1using MongoDB.Bson;
2using MongoDB.Driver;
3
4// connect to your Atlas deployment
5var uri = "<connection-string>";
6
7var client = new MongoClient(uri);
8
9var db = client.GetDatabase("sample_mflix");
10var collection = db.GetCollection<BsonDocument>("movies");
11
12// define your MongoDB Search index
13var index = new CreateSearchIndexModel(
14 "default", new BsonDocument
15 {
16 { "mappings", new BsonDocument
17 {
18 { "dynamic", false },
19 { "fields", new BsonDocument
20 {
21 { "title", new BsonDocument
22 {
23 { "type", "string" }
24 }
25 }
26 }
27 }
28 }
29 }
30 });
31
32var result = collection.SearchIndexes.CreateOne(index);
33Console.WriteLine($"New index name: {result}");
1

In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project and initialize your project in that directory:

1# Create a new directory and initialize the project
2mkdir atlas-search-project && cd atlas-search-project
3go mod init atlas-search-project
4
5# Add the MongoDB Go Driver to your project
6go get go.mongodb.org/mongo-driver/v2/mongo

For more detailed installation instructions, see the MongoDB Go Driver documentation.

2

Create a create_index.go file in your project directory, and copy and paste the following code into the file.

create_index.go
1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7
8 "go.mongodb.org/mongo-driver/v2/bson"
9 "go.mongodb.org/mongo-driver/v2/mongo"
10 "go.mongodb.org/mongo-driver/v2/mongo/options"
11)
12
13func main() {
14 ctx := context.Background()
15 uri := "<connection-string>"
16 client, err := mongo.Connect(options.Client().
17 ApplyURI(uri))
18 if err != nil {
19 panic(err)
20 }
21
22 defer func() {
23 if err := client.Disconnect(context.TODO()); err != nil {
24 panic(err)
25 }
26 }()
27
28 coll := client.Database("<database>").Collection("<collection>")
29 const indexName = "default"
30 opts := options.SearchIndexes().SetName(indexName).SetType("search")
31
32 // Define the MongoDB Search index for the string field
33 searchIndexModel := mongo.SearchIndexModel{
34 Definition: bson.D{
35 {"mappings", bson.D{
36 {"dynamic", false},
37 {"fields", bson.D{
38 {"<field-name>", bson.D{
39 {"type", "string"},
40 {"analyzer", "<analyzer-name>"},
41 {"searchAnalyzer", "<search-analyzer-name>"},
42 {"indexOptions", "docs|freqs|positions|offsets"}
43 {"store", true|false},
44 {"ignoreAbove", <integer>},
45 {"similarity", bson.D{{"type", "bm25|boolean|stableTfl"}}},
46 {"multi", bson.D{<string-field-definition>}},
47 {"norms", "include|omit"},
48 }},
49 }},
50 }},
51 },
52 Options: opts,
53 }
54
55 // Create the index
56 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel)
57 if err != nil {
58 log.Fatalf("Failed to create the Atlas Search index: %v", err)
59 }
60
61 fmt.Println("Name of index created: " + searchIndexName)
62}

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.

Note

For a local or self-managed deployment, your connection string should use the following format:

mongodb://localhost:<port-number>/?directConnection=true

To learn more, see Connection Strings.

3
go run create_index.go
New index name: default

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7
8 "go.mongodb.org/mongo-driver/v2/bson"
9 "go.mongodb.org/mongo-driver/v2/mongo"
10 "go.mongodb.org/mongo-driver/v2/mongo/options"
11)
12
13func main() {
14 ctx := context.Background()
15 uri := "<connection-string>"
16 client, err := mongo.Connect(options.Client().
17 ApplyURI(uri))
18 if err != nil {
19 panic(err)
20 }
21
22 defer func() {
23 if err := client.Disconnect(context.TODO()); err != nil {
24 panic(err)
25 }
26 }()
27
28 coll := client.Database("sample_mflix").Collection("movies")
29 const indexName = "default"
30 opts := options.SearchIndexes().SetName(indexName).SetType("search")
31
32 // Define the MongoDB Search index for the string field
33 searchIndexModel := mongo.SearchIndexModel{
34 Definition: bson.D{
35 {"mappings", bson.D{
36 {"dynamic", false},
37 {"fields", bson.D{
38 {"title", bson.D{
39 {"type", "string"},
40 }},
41 }},
42 }},
43 },
44 Options: opts,
45 }
46
47 // Create the index
48 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel)
49 if err != nil {
50 log.Fatalf("Failed to create the Atlas Search index: %v", err)
51 }
52
53 fmt.Println("Name of index created: " + searchIndexName)
54}
1

In your IDE, create a new Maven or Gradle project. Add the Bill of Materials (BOM) for MongoDB JVM artifacts to your project to organize dependency versions. The BOM simplifies dependency management by ensuring that you maintain consistent and compatible versions of dependencies, such as between the Java driver and the core driver library. Use the BOM to avoid version conflicts and simplify upgrades.

Select from the following Maven and Gradle tabs to view instructions for adding the BOM for each dependency manager:

Add the following code to the dependencyManagement list in your pom.xml file:

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-bom</artifactId>
<version>5.5.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

To view a list of dependencies that the BOM manages, see the mongodb-driver-bom dependency listing on the Maven Repository website.

After adding the BOM, select from the following Maven and Gradle tabs to view instructions for adding the MongoDB Java Sync Driver as a dependency in your project:

Add the following code to the dependencies array in your Maven project's pom.xml file:

pom.xml
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.11.1</version>
</dependency>
</dependencies>

Run your package manager to install the dependencies to your project.

For more detailed installation instructions and version compatibility, see the MongoDB Java Driver documentation.

2

In your project's base package directory, create a file called CreateIndex.java and copy and paste the following code into this file:

CreateIndex.java
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6
7public class CreateIndex {
8 public static void main(String[] args) {
9 // connect to your Atlas cluster
10 String uri = "<connection-string>";
11
12 try (MongoClient mongoClient = MongoClients.create(uri)) {
13 // set namespace
14 MongoDatabase database = mongoClient.getDatabase("<database>");
15 MongoCollection<Document> collection = database.getCollection("<collection>");
16
17 Document index = new Document("mappings",
18 new Document("dynamic", true|false),
19 .append("fields", new Document("<field-name>",
20 new Document("type", "string")
21 .append("analyzer", "<analyzer-name>")
22 .append("searchAnalyzer", "<search-analyzer-name>")
23 .append("indexOptions", "docs|freqs|positions|offsets")
24 .append("store", true|false)
25 .append("ignoreAbove", <integer>)
26 .append("similarity", new Document("type", "bm25|boolean|stableTfl"))
27 .append("multi", new Document(<string-field-definition>))
28 .append("norms", "include|omit")
29 )));
30
31 String result = collection.createSearchIndex(index);
32 System.out.println("New index name: " + result);
33 }
34 }
35}

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.

Note

For a local or self-managed deployment, your connection string should use the following format:

mongodb://localhost:<port-number>/?directConnection=true

To learn more, see Connection Strings.

3
javac CreateIndex.java
java CreateIndex
New index name: default

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6
7public class IndexExample {
8 public static void main(String[] args) {
9 // connect to your Atlas cluster
10 String uri = "<connection-string>";
11
12 try (MongoClient mongoClient = MongoClients.create(uri)) {
13 // set namespace
14 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
15 MongoCollection<Document> collection = database.getCollection("movies");
16
17 Document index = new Document("mappings",
18 new Document("dynamic", false),
19 .append("similarity": { "type": "bm25" }),
20 .append("fields", new Document("title", new Document("type", "string"))));
21 String result = collection.createSearchIndex(index);
22 System.out.println("New index name: " + result);
23 }
24 }
25}
1
# Create a new directory and initialize the project
mkdir atlas-search-project && cd atlas-search-project
npm init -y
# Add the MongoDB Node.js Driver to your project
npm install mongodb

For detailed installation instructions, see the MongoDB Node Driver documentation.

2

Create a create-index.js file in your project directory, and copy and paste the following code into the file.

create-index.js
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri =
5 "<connection-string>";
6
7const client = new MongoClient(uri);
8
9async function run() {
10 try {
11
12 // set namespace
13 const database = client.db("<database>");
14 const collection = database.collection("<collection>");
15
16 // define your MongoDB Search index
17 const index = {
18 name: "default",
19 definition: {
20 /* search index definition fields */
21 "mappings": {
22 "dynamic": true|false,
23 "fields": {
24 "<field-name>": {
25 "type": "string",
26 "analyzer": "<analyzer-name>",
27 "searchAnalyzer": "<search-analyzer-name>",
28 "indexOptions": "docs|freqs|positions|offsets",
29 "store": true|false,
30 "ignoreAbove": <integer>,
31 "similarity": { "type": "bm25|boolean|stableTfl" },
32 "multi": { <string-field-definition> },
33 "norms": "include|omit"
34 }
35 }
36 }
37 }
38 }
39
40 // run the helper method
41 const result = await collection.createSearchIndex(index);
42 console.log("New index name: " + result);
43 } finally {
44 await client.close();
45 }
46}
47
48run().catch(console.dir);

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.

Note

For a local or self-managed deployment, your connection string should use the following format:

mongodb://localhost:<port-number>/?directConnection=true

To learn more, see Connection Strings.

3
node create-index.js
New index name: default

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri =
5 "<connection-string>";
6
7const client = new MongoClient(uri);
8
9async function run() {
10 try {
11
12 // set namespace
13 const database = client.db("sample_mflix");
14 const collection = database.collection("movies");
15
16 // define your MongoDB Search index
17 const index = {
18 name: "default",
19 definition: {
20 "mappings": {
21 "dynamic": false,
22 "fields": {
23 "title": {
24 "type": "string"
25 }
26 }
27 }
28 }
29 }
30
31 // run the helper method
32 const result = await collection.createSearchIndex(index);
33 console.log("New index name: " + result);
34 } finally {
35 await client.close();
36 }
37}
38
39run().catch(console.dir);
1
# Create a new directory for the project
mkdir atlas-search-project && cd atlas-search-project
# Install PyMongo
pip install pymongo

For detailed installation instructions, see MongoDB Python Driver (PyMongo).

2

Paste the following code into a file named create_index.py.

create_index.py
1from pymongo import MongoClient
2from pymongo.operations import SearchIndexModel
3
4# connect to your Atlas deployment
5uri = "<connection-string>"
6client = MongoClient(uri)
7
8# set namespace
9database = client["<database>"]
10collection = database["<collection>"]
11
12# define your MongoDB Search index
13search_index_model = SearchIndexModel(
14 definition={
15 "mappings": {
16 "dynamic": True|False,
17 "fields": {
18 "<field_name>":{
19 "type": "string",
20 "analyzer": "<analyzer-name>",
21 "searchAnalyzer": "<search-analyzer-name>",
22 "indexOptions": "docs|freqs|positions|offsets",
23 "store": True|False,
24 "ignoreAbove": <integer>,
25 "similarity": { "type": "bm25|boolean|stableTfl" },
26 "multi": { <string-field-definition> },
27 "norms": "include|omit"
28 }
29 }
30 },
31 },
32 name="default",
33)
34
35# create the index
36result = collection.create_search_index(model=search_index_model)
37print(f"New index name: {result}")

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.

Note

For a local or self-managed deployment, your connection string should use the following format:

mongodb://localhost:<port-number>/?directConnection=true

To learn more, see Connection Strings.

3
python create_index.py
New index name: default

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1from pymongo import MongoClient
2from pymongo.operations import SearchIndexModel
3
4# connect to your Atlas deployment
5uri = "<connection-string>"
6client = MongoClient(uri)
7
8# set namespace
9database = client["sample_mflix"]
10collection = database["movies"]
11
12# define your MongoDB Search index
13search_index_model = SearchIndexModel(
14 definition={
15 "mappings": {
16 "dynamic": False,
17 "fields": {
18 "title": {
19 "type": "string"
20 }
21 }
22 },
23 },
24 name="default",
25)
26
27# create the index
28result = collection.create_search_index(model=search_index_model)
29print(f"New index name: {result}")
1
search-index.json
1{
2 "name": "default",
3 "collectionName": "<collection>",
4 "database": "<database>",
5 "definition": {
6 "mappings": {
7 "dynamic": true|false,
8 "fields": {
9 "<field-name>": {
10 "type": "string",
11 "analyzer": "<atlas-search-analyzer>",
12 "searchAnalyzer": "<atlas-search-analyzer>",
13 "indexOptions": "docs|freqs|positions|offsets",
14 "store": true|false,
15 "ignoreAbove": <integer>,
16 "similarity": { "type": "bm25|boolean|stableTfl" },
17 "multi": { <string-field-definition> },
18 "norms": "include|omit"
19 }
20 }
21 }
22 }
23 }
24}
2

In your terminal, connect to your local deployment from the Atlas CLI. To learn more, see Connect from the Atlas CLI.

3

Run the atlas deployments search indexes create command in your terminal, replacing <path-to-file> with the path to the search-index.json file:

atlas deployments search indexes create --file <path-to-file>

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1{
2 "name": "default",
3 "collectionName": "movies",
4 "database": "sample_mflix",
5 "definition": {
6 "mappings": {
7 "dynamic": false,
8 "fields": {
9 "title": {
10 "type": "string"
11 }
12 }
13 }
14 }
15}
1

Open Compass and connect to your cluster. For detailed instructions, see Connect to a Cluster via Compass.

2

On the Database screen, click the name of the database, then click the name of the collection.

3
  1. Click the Indexes tab, then select Search Indexes.

  2. Click Create Atlas Search Index to open the index creation dialog box.

  3. Specify a name for the index.

    Your MongoDB Search index is named default by default. If you keep this name, then your index will be the default Search index for any MongoDB Search query that does not specify a different index option in its operators. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.

  4. Specify the JSON MongoDB Search index definition.

    1{
    2 "mappings": {
    3 "dynamic": true|false,
    4 "fields": {
    5 "<field-name>": {
    6 "type": "string",
    7 "analyzer": "<atlas-search-analyzer>",
    8 "searchAnalyzer": "<atlas-search-analyzer>",
    9 "indexOptions": "docs|freqs|positions|offsets",
    10 "store": true|false,
    11 "ignoreAbove": <integer>,
    12 "similarity": { "type": "bm25|boolean|stableTfl" },
    13 "multi": { <string-field-definition> },
    14 "norms": "include|omit"
    15 }
    16 }
    17 }
    18}
  5. Click Create Search Index.

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1{
2 "mappings": {
3 "dynamic": false,
4 "fields": {
5 "title": {
6 "type": "string"
7 }
8 }
9 }
10}
1

In your terminal, connect to your Atlas cloud-hosted deployment or local deployment from mongosh. For detailed instructions on how to connect, see Connect to a Deployment.

2
use <database>
switched to db <database>
3
db.<collection>.createSearchIndex(
"default",
{
"mappings": {
"dynamic": true|false,
"fields": {
"<field-name>": {
"type": "string"
"analyzer": "<atlas-search-analyzer>",
"searchAnalyzer": "<atlas-search-analyzer>",
"indexOptions": "docs|freqs|positions|offsets",
"store": true|false,
"ignoreAbove": <integer>,
"similarity": { "type": "bm25|boolean|stableTfl" }
"multi": { <string-field-definition> },
"norms": "include|omit"
},
}
}
}
)
default

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1db.movies.createSearchIndex(
2 {
3 "mappings": {
4 "dynamic": false,
5 "fields": {
6 "title": {
7 "type": "string"
8 }
9 }
10 }
11 }
12)
1

In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project for this project:

1# Create a new directory for the project
2mkdir atlas-search-project && cd atlas-search-project

Add the C driver to your project by following the instructions in the MongoDB C Driver documentation.

2

Create a create_index.c file in your project directory, and copy and paste the following code into the file.

create_index.c
1#include <mongoc/mongoc.h>
2#include <stdlib.h>
3
4int main (void)
5{
6 mongoc_client_t *client = NULL;
7 mongoc_collection_t *collection = NULL;
8 mongoc_database_t *database = NULL;
9 bson_error_t error;
10 bson_t cmd = BSON_INITIALIZER;
11 bool ok = true;
12
13 mongoc_init();
14
15 // Connect to your Atlas deployment
16 client = mongoc_client_new("<connectionString>");
17 if (!client) {
18 fprintf(stderr, "Failed to create a MongoDB client.\n");
19 ok = false;
20 goto cleanup;
21 }
22
23 // Access your database and collection
24 database = mongoc_client_get_database(client, "<databaseName>");
25 collection = mongoc_database_get_collection(database, "<collectionName>");
26
27 // Specify the command and the new index
28 const char *cmd_str = BSON_STR({
29 "createSearchIndexes" : "<collectionName>",
30 "indexes" : [ {
31 "name" : "default",
32 "definition" : {
33 "mappings": {
34 "dynamic": true|false,
35 "fields": {
36 "<fieldName>" : {
37 "type": "string"
38 "analyzer": "<atlas-search-analyzer>",
39 "searchAnalyzer": "<atlas-search-analyzer>",
40 "indexOptions": "docs|freqs|positions|offsets",
41 "store": true|false,
42 "ignoreAbove": <integer>,
43 "similarity": { "type": "bm25|boolean|stableTfl" },
44 "multi": { <string-field-definition> },
45 "norms": "include|omit"
46 }
47 },
48 },
49 }
50 } ]
51 });
52
53 // Convert your command to BSON
54 if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) {
55 fprintf(stderr, "Failed to parse command: %s\n", error.message);
56 ok = false;
57 goto cleanup;
58 }
59
60 // Create the MongoDB Search index by running the command
61 if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) {
62 fprintf(stderr, "Failed to run createSearchIndexes: %s\n", error.message);
63 ok = false;
64 goto cleanup;
65 }
66 printf ("Index created!\n");
67
68cleanup:
69 mongoc_collection_destroy (collection);
70 mongoc_client_destroy (client);
71 mongoc_database_destroy (database);
72 bson_destroy (&cmd);
73 mongoc_cleanup ();
74 return ok ? EXIT_SUCCESS : EXIT_FAILURE;
75}

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.

Note

For a local or self-managed deployment, your connection string should use the following format:

mongodb://localhost:<port-number>/?directConnection=true

To learn more, see Connection Strings.

3

To configure your application, create a CMakeLists.txt file in your project directory. Then, add the following code to the file:

CMakeLists.txt
1cmake_minimum_required(VERSION 3.11)
2project(atlas-search-index LANGUAGES C)
3add_executable (index.out create_index.c)
4find_package(mongoc <version> REQUIRED)
5target_link_libraries(index.out mongoc::mongoc)

The preceding code performs the following actions:

  • Configures a C project.

  • Creates a index.out executable for your application.

  • Finds and requires the C driver. Replace the <version> placeholder with your C driver version number, such as 2.0.0.

  • Links the program to the libmongoc library.

Note

In the sample CMakeLists.txt file, the mongoc::mongoc target points to either the static library or the shared library. The library type depends on which one is available and whichever type the user specifies in the MONGOC_DEFAULT_IMPORTED_LIBRARY_TYPE CMake configuration setting. If you don't set this value and both library types are available, mongoc::mongoc uses the static library.

You can use the mongoc::static target to explicitly use the static library or the mongoc::shared target to use the shared library.

4

In your terminal, run the following commands to build and run this application:

cmake -S. -Bcmake-build
cmake --build cmake-build --target index.out
./cmake-build/index.out
Index created!

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1#include <mongoc/mongoc.h>
2#include <stdlib.h>
3
4int main (void)
5{
6 mongoc_client_t *client = NULL;
7 mongoc_collection_t *collection = NULL;
8 mongoc_database_t *database = NULL;
9 bson_error_t error;
10 bson_t cmd = BSON_INITIALIZER;
11 bool ok = true;
12
13 mongoc_init();
14
15 // Connect to your Atlas deployment
16 client = mongoc_client_new("<connectionString>");
17 if (!client) {
18 fprintf(stderr, "Failed to create a MongoDB client.\n");
19 ok = false;
20 goto cleanup;
21 }
22
23 // Access your database and collection
24 database = mongoc_client_get_database(client, "sample_mflix");
25 collection = mongoc_database_get_collection(database, "movies");
26
27 // Specify the command and the new index
28 const char *cmd_str = BSON_STR({
29 "createSearchIndexes" : "movies",
30 "indexes" : [ {
31 "name" : "default",
32 "definition" : {
33 "mappings": {
34 "dynamic": false,
35 "fields": {
36 "title" : {
37 "type": "string"
38 }
39 }
40 },
41 }
42 } ]
43 });
44
45 // Convert your command to BSON
46 if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) {
47 fprintf(stderr, "Failed to parse command: %s\n", error.message);
48 ok = false;
49 goto cleanup;
50 }
51
52 // Create the MongoDB Search index by running the command
53 if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) {
54 fprintf(stderr, "Failed to run createSearchIndexes: %s\n", error.message);
55 ok = false;
56 goto cleanup;
57 }
58 printf ("Index created!\n");
59
60cleanup:
61 mongoc_collection_destroy (collection);
62 mongoc_client_destroy (client);
63 mongoc_database_destroy (database);
64 bson_destroy (&cmd);
65 mongoc_cleanup ();
66 return ok ? EXIT_SUCCESS : EXIT_FAILURE;
67}
1

In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project for this project:

# Create a new directory for the project
mkdir atlas-search-project && cd atlas-search-project

For more detailed installation instructions, see the MongoDB C++ Driver documentation.

2

Create a CreateIndex.cpp file in your project directory, and copy and paste the following code into the file.

CreateIndex.cpp
1#include <iostream>
2
3#include <bsoncxx/builder/basic/document.hpp>
4#include <bsoncxx/json.hpp>
5#include <mongocxx/client.hpp>
6#include <mongocxx/instance.hpp>
7#include <mongocxx/uri.hpp>
8
9using bsoncxx::builder::basic::kvp;
10using bsoncxx::builder::basic::make_document;
11
12
13int main(){
14
15 mongocxx::instance instance;
16 mongocxx::uri uri("<connection string>");
17 mongocxx::client client(uri);
18
19 auto db = client["<database>"];
20 auto collection = db["<collection>"];
21
22 // instantiate a ``mongocxx::search_index_view`` on your collection
23 auto siv = collection.search_indexes();
24
25 {
26 auto name = "default";
27 auto definition = make_document(
28 kvp("mappings", make_document(
29 kvp("dynamic", true|false),
30 kvp("fields", make_document(
31 kvp("<field-name>", make_document(
32 kvp("type", "string"),
33 kvp("analyzer", "<analyzer-name>"),
34 kvp("searchAnalyzer", "<search-analyzer-name>"),
35 kvp("indexOptions", "docs|freqs|positions|offsets"),
36 kvp("store", true|false),
37 kvp("ignoreAbove", <integer>),
38 kvp("similarity", make_document( kvp("type", "bm25|boolean|stableTfl"))),
39 kvp("multi", make_document( <string-field-definition> )),
40 kvp("norms", "include|omit")
41 ))
42 ))
43 ))
44 );
45
46 auto model = mongocxx::search_index_model(name, definition.view());
47
48 // Create the search index
49 auto result = siv.create_one(model);
50 std::cout << "New index name: " << result << std::endl;
51 }
52}

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.

Note

For a local or self-managed deployment, your connection string should use the following format:

mongodb://localhost:<port-number>/?directConnection=true

To learn more, see Connection Strings.

3
c++ --std=c++17 CreateIndex.cpp $(pkg-config --cflags --libs libmongocxx) -o ./app.out
./app.out
New index name: default

Tip

MacOS Error

MacOS users might see the following error after running the preceding commands:

dyld[54430]: Library not loaded: @rpath/libmongocxx._noabi.dylib

To resolve this error, use the -Wl,-rpath linker option to set the @rpath, as shown in the following code:

c++ --std=c++17 CreateIndex.cpp -Wl,-rpath,/usr/local/lib/ $(pkg-config --cflags --libs libmongocxx) -o ./app.out
./app.out

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1#include <iostream>
2
3#include <bsoncxx/builder/basic/document.hpp>
4#include <bsoncxx/json.hpp>
5#include <mongocxx/client.hpp>
6#include <mongocxx/instance.hpp>
7#include <mongocxx/uri.hpp>
8
9using bsoncxx::builder::basic::kvp;
10using bsoncxx::builder::basic::make_document;
11
12
13int main(){
14
15 mongocxx::instance instance;
16 mongocxx::uri uri("<connection string>");
17 mongocxx::client client(uri);
18
19 auto db = client["sample_mflix"];
20 auto collection = db["movies"];
21
22 // instantiate a ``mongocxx::search_index_view`` on your collection
23 auto siv = collection.search_indexes();
24
25 {
26 auto name = "default";
27 auto definition = make_document(
28 kvp("mappings", make_document(
29 kvp("dynamic", false),
30 kvp("fields", make_document(
31 kvp("title", make_document(
32 kvp("type", "string")
33 ))
34 ))
35 ))
36 );
37
38 auto model = mongocxx::search_index_model(name, definition.view());
39
40 // Create the search index
41 auto result = siv.create_one(model);
42 std::cout << "New index name: " << result << std::endl;
43 }
44}
1

In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project and initialize your project in that directory:

# Create a new directory and initialize the project
mkdir atlas-search-project && cd atlas-search-project
dotnet new console
# Add the MongoDB .NET/C# Driver to your project
dotnet add package MongoDB.Driver

For more detailed installation instructions, see the MongoDB .NET/C# Driver documentation.

2

Paste the following code into the Program.cs file.

Program.cs
1using MongoDB.Bson;
2using MongoDB.Driver;
3
4// connect to your Atlas deployment
5var uri = "<connection-string>";
6
7var client = new MongoClient(uri);
8
9var db = client.GetDatabase("<database>");
10var collection = db.GetCollection<BsonDocument>("<collection>");
11
12// define your MongoDB Search index
13var index = new CreateSearchIndexModel(
14 "default", new BsonDocument
15 {
16 { "mappings", new BsonDocument
17 {
18 { "dynamic", true|false },
19 { "fields", new BsonDocument
20 {
21 { "<field-name>", new BsonDocument
22 {
23 { "type", "string" },
24 { "analyzer", "<analyzer-name>"},
25 { "searchAnalyzer", "<search-analyzer-name>"},
26 { "indexOptions", "docs|freqs|positions|offsets"},
27 { "store", true|false },
28 { "ignoreAbove", <integer> },
29 { "similarity", new BsonDocument { { "type", "bm25|boolean|stableTfl" } } },
30 { "multi", new BsonDocument { <string-field-definition> },
31 { "norms", "include|omit" }
32 }
33 }
34 }
35 }
36 }
37 }
38 });
39
40var result = collection.SearchIndexes.CreateOne(index);
41Console.WriteLine($"New index name: {result}");

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.

Note

For a local or self-managed deployment, your connection string should use the following format:

mongodb://localhost:<port-number>/?directConnection=true

To learn more, see Connection Strings.

3
dotnet run Program.cs
New index name: default

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1using MongoDB.Bson;
2using MongoDB.Driver;
3
4// connect to your Atlas deployment
5var uri = "<connection-string>";
6
7var client = new MongoClient(uri);
8
9var db = client.GetDatabase("sample_mflix");
10var collection = db.GetCollection<BsonDocument>("movies");
11
12// define your MongoDB Search index
13var index = new CreateSearchIndexModel(
14 "default", new BsonDocument
15 {
16 { "mappings", new BsonDocument
17 {
18 { "dynamic", false },
19 { "fields", new BsonDocument
20 {
21 { "title", new BsonDocument
22 {
23 { "type", "string" }
24 }
25 }
26 }
27 }
28 }
29 }
30 });
31
32var result = collection.SearchIndexes.CreateOne(index);
33Console.WriteLine($"New index name: {result}");
1

In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project and initialize your project in that directory:

1# Create a new directory and initialize the project
2mkdir atlas-search-project && cd atlas-search-project
3go mod init atlas-search-project
4
5# Add the MongoDB Go Driver to your project
6go get go.mongodb.org/mongo-driver/v2/mongo

For more detailed installation instructions, see the MongoDB Go Driver documentation.

2

Create a create_index.go file in your project directory, and copy and paste the following code into the file.

create_index.go
1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7
8 "go.mongodb.org/mongo-driver/v2/bson"
9 "go.mongodb.org/mongo-driver/v2/mongo"
10 "go.mongodb.org/mongo-driver/v2/mongo/options"
11)
12
13func main() {
14 ctx := context.Background()
15 uri := "<connection-string>"
16 client, err := mongo.Connect(options.Client().
17 ApplyURI(uri))
18 if err != nil {
19 panic(err)
20 }
21
22 defer func() {
23 if err := client.Disconnect(context.TODO()); err != nil {
24 panic(err)
25 }
26 }()
27
28 coll := client.Database("<database>").Collection("<collection>")
29 const indexName = "default"
30 opts := options.SearchIndexes().SetName(indexName).SetType("search")
31
32 // Define the MongoDB Search index for the string field
33 searchIndexModel := mongo.SearchIndexModel{
34 Definition: bson.D{
35 {"mappings", bson.D{
36 {"dynamic", false},
37 {"fields", bson.D{
38 {"<field-name>", bson.D{
39 {"type", "string"},
40 {"analyzer", "<analyzer-name>"},
41 {"searchAnalyzer", "<search-analyzer-name>"},
42 {"indexOptions", "docs|freqs|positions|offsets"}
43 {"store", true|false},
44 {"ignoreAbove", <integer>},
45 {"similarity", bson.D{{"type", "bm25|boolean|stableTfl"}}},
46 {"multi", bson.D{<string-field-definition>}},
47 {"norms", "include|omit"},
48 }},
49 }},
50 }},
51 },
52 Options: opts,
53 }
54
55 // Create the index
56 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel)
57 if err != nil {
58 log.Fatalf("Failed to create the Atlas Search index: %v", err)
59 }
60
61 fmt.Println("Name of index created: " + searchIndexName)
62}

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.

Note

For a local or self-managed deployment, your connection string should use the following format:

mongodb://localhost:<port-number>/?directConnection=true

To learn more, see Connection Strings.

3
go run create_index.go
New index name: default

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7
8 "go.mongodb.org/mongo-driver/v2/bson"
9 "go.mongodb.org/mongo-driver/v2/mongo"
10 "go.mongodb.org/mongo-driver/v2/mongo/options"
11)
12
13func main() {
14 ctx := context.Background()
15 uri := "<connection-string>"
16 client, err := mongo.Connect(options.Client().
17 ApplyURI(uri))
18 if err != nil {
19 panic(err)
20 }
21
22 defer func() {
23 if err := client.Disconnect(context.TODO()); err != nil {
24 panic(err)
25 }
26 }()
27
28 coll := client.Database("sample_mflix").Collection("movies")
29 const indexName = "default"
30 opts := options.SearchIndexes().SetName(indexName).SetType("search")
31
32 // Define the MongoDB Search index for the string field
33 searchIndexModel := mongo.SearchIndexModel{
34 Definition: bson.D{
35 {"mappings", bson.D{
36 {"dynamic", false},
37 {"fields", bson.D{
38 {"title", bson.D{
39 {"type", "string"},
40 }},
41 }},
42 }},
43 },
44 Options: opts,
45 }
46
47 // Create the index
48 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel)
49 if err != nil {
50 log.Fatalf("Failed to create the Atlas Search index: %v", err)
51 }
52
53 fmt.Println("Name of index created: " + searchIndexName)
54}
1

In your IDE, create a new Maven or Gradle project. Add the Bill of Materials (BOM) for MongoDB JVM artifacts to your project to organize dependency versions. The BOM simplifies dependency management by ensuring that you maintain consistent and compatible versions of dependencies, such as between the Java driver and the core driver library. Use the BOM to avoid version conflicts and simplify upgrades.

Select from the following Maven and Gradle tabs to view instructions for adding the BOM for each dependency manager:

Add the following code to the dependencyManagement list in your pom.xml file:

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-bom</artifactId>
<version>5.5.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

To view a list of dependencies that the BOM manages, see the mongodb-driver-bom dependency listing on the Maven Repository website.

After adding the BOM, select from the following Maven and Gradle tabs to view instructions for adding the MongoDB Java Sync Driver as a dependency in your project:

Add the following code to the dependencies array in your Maven project's pom.xml file:

pom.xml
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.11.1</version>
</dependency>
</dependencies>

Run your package manager to install the dependencies to your project.

For more detailed installation instructions and version compatibility, see the MongoDB Java Driver documentation.

2

In your project's base package directory, create a file called CreateIndex.java and copy and paste the following code into this file:

CreateIndex.java
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6
7public class CreateIndex {
8 public static void main(String[] args) {
9 // connect to your Atlas cluster
10 String uri = "<connection-string>";
11
12 try (MongoClient mongoClient = MongoClients.create(uri)) {
13 // set namespace
14 MongoDatabase database = mongoClient.getDatabase("<database>");
15 MongoCollection<Document> collection = database.getCollection("<collection>");
16
17 Document index = new Document("mappings",
18 new Document("dynamic", true|false),
19 .append("fields", new Document("<field-name>",
20 new Document("type", "string")
21 .append("analyzer", "<analyzer-name>")
22 .append("searchAnalyzer", "<search-analyzer-name>")
23 .append("indexOptions", "docs|freqs|positions|offsets")
24 .append("store", true|false)
25 .append("ignoreAbove", <integer>)
26 .append("similarity", new Document("type", "bm25|boolean|stableTfl"))
27 .append("multi", new Document(<string-field-definition>))
28 .append("norms", "include|omit")
29 )));
30
31 String result = collection.createSearchIndex(index);
32 System.out.println("New index name: " + result);
33 }
34 }
35}

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.

Note

For a local or self-managed deployment, your connection string should use the following format:

mongodb://localhost:<port-number>/?directConnection=true

To learn more, see Connection Strings.

3
javac CreateIndex.java
java CreateIndex
New index name: default

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6
7public class IndexExample {
8 public static void main(String[] args) {
9 // connect to your Atlas cluster
10 String uri = "<connection-string>";
11
12 try (MongoClient mongoClient = MongoClients.create(uri)) {
13 // set namespace
14 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
15 MongoCollection<Document> collection = database.getCollection("movies");
16
17 Document index = new Document("mappings",
18 new Document("dynamic", false),
19 .append("similarity": { "type": "bm25" }),
20 .append("fields", new Document("title", new Document("type", "string"))));
21 String result = collection.createSearchIndex(index);
22 System.out.println("New index name: " + result);
23 }
24 }
25}
1
# Create a new directory and initialize the project
mkdir atlas-search-project && cd atlas-search-project
npm init -y
# Add the MongoDB Node.js Driver to your project
npm install mongodb

For detailed installation instructions, see the MongoDB Node Driver documentation.

2

Create a create-index.js file in your project directory, and copy and paste the following code into the file.

create-index.js
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri =
5 "<connection-string>";
6
7const client = new MongoClient(uri);
8
9async function run() {
10 try {
11
12 // set namespace
13 const database = client.db("<database>");
14 const collection = database.collection("<collection>");
15
16 // define your MongoDB Search index
17 const index = {
18 name: "default",
19 definition: {
20 /* search index definition fields */
21 "mappings": {
22 "dynamic": true|false,
23 "fields": {
24 "<field-name>": {
25 "type": "string",
26 "analyzer": "<analyzer-name>",
27 "searchAnalyzer": "<search-analyzer-name>",
28 "indexOptions": "docs|freqs|positions|offsets",
29 "store": true|false,
30 "ignoreAbove": <integer>,
31 "similarity": { "type": "bm25|boolean|stableTfl" },
32 "multi": { <string-field-definition> },
33 "norms": "include|omit"
34 }
35 }
36 }
37 }
38 }
39
40 // run the helper method
41 const result = await collection.createSearchIndex(index);
42 console.log("New index name: " + result);
43 } finally {
44 await client.close();
45 }
46}
47
48run().catch(console.dir);

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.

Note

For a local or self-managed deployment, your connection string should use the following format:

mongodb://localhost:<port-number>/?directConnection=true

To learn more, see Connection Strings.

3
node create-index.js
New index name: default

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri =
5 "<connection-string>";
6
7const client = new MongoClient(uri);
8
9async function run() {
10 try {
11
12 // set namespace
13 const database = client.db("sample_mflix");
14 const collection = database.collection("movies");
15
16 // define your MongoDB Search index
17 const index = {
18 name: "default",
19 definition: {
20 "mappings": {
21 "dynamic": false,
22 "fields": {
23 "title": {
24 "type": "string"
25 }
26 }
27 }
28 }
29 }
30
31 // run the helper method
32 const result = await collection.createSearchIndex(index);
33 console.log("New index name: " + result);
34 } finally {
35 await client.close();
36 }
37}
38
39run().catch(console.dir);
1
# Create a new directory for the project
mkdir atlas-search-project && cd atlas-search-project
# Install PyMongo
pip install pymongo

For detailed installation instructions, see MongoDB Python Driver (PyMongo).

2

Paste the following code into a file named create_index.py.

create_index.py
1from pymongo import MongoClient
2from pymongo.operations import SearchIndexModel
3
4# connect to your Atlas deployment
5uri = "<connection-string>"
6client = MongoClient(uri)
7
8# set namespace
9database = client["<database>"]
10collection = database["<collection>"]
11
12# define your MongoDB Search index
13search_index_model = SearchIndexModel(
14 definition={
15 "mappings": {
16 "dynamic": True|False,
17 "fields": {
18 "<field_name>":{
19 "type": "string",
20 "analyzer": "<analyzer-name>",
21 "searchAnalyzer": "<search-analyzer-name>",
22 "indexOptions": "docs|freqs|positions|offsets",
23 "store": True|False,
24 "ignoreAbove": <integer>,
25 "similarity": { "type": "bm25|boolean|stableTfl" },
26 "multi": { <string-field-definition> },
27 "norms": "include|omit"
28 }
29 }
30 },
31 },
32 name="default",
33)
34
35# create the index
36result = collection.create_search_index(model=search_index_model)
37print(f"New index name: {result}")

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.

Note

For a local or self-managed deployment, your connection string should use the following format:

mongodb://localhost:<port-number>/?directConnection=true

To learn more, see Connection Strings.

3
python create_index.py
New index name: default

The MongoDB Search string type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. Value must be string.

analyzer

string

Optional

Name of a built-in or custom analyzer to use for indexing the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for the index if specified.

  2. The lucene.standard analyzer.

searchAnalyzer

string

Optional

Analyzer to use when querying the field. If you don't specify a value, inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

indexOptions

string

Optional

Amount of information to store for the indexed field. Value can be one of the following:

  • docs - Only indexes documents. The frequency and position of the indexed term are ignored. Only a single occurence of the term is reflected in the score.

  • freqs - Only indexes documents and term frequency. The position of the indexed term is ignored. Use this value if you only need TF-IDF based scoring and don't run phrase, span, or highlight queries.

  • positions - Indexes documents, term frequency, and term positions. This value is required for phrase and span operations.

  • offsets - (Default) Indexes documents, term frequency, term positions, and term offsets. This value is required for highlight.

Each successive value stores more information and increases the index size. If you choose offsets over freqs, your index size can increase by 2.5 to 3 times because positions and offsets store an integer for each token occurrence.

offsets

store

boolean

Optional

Flag that indicates whether to store the exact document text as well as the analyzed values in the index. Value can be true or false. The value for this option must be true for highlight.

To reduce the index size and performance footprint, we recommend setting store to false. To learn more, see Improve MongoDB Search Index Performance.

When you set store to false, you can't run highlight queries, so you don't need term offsets. In this case, set the indexOptions option to positions instead of the default offsets to further reduce the index size while still supporting phrase and span queries.

true

ignoreAbove

int

Optional

Maximum number of characters in the value of the field to index. MongoDB Search doesn't index if the field value is greater than the specified number of characters.

similarity.type

String

Optional

Name of the similarity algorithm to use with this string mapping when scoring with the text, phrase, or queryString operators. Value can be one of the following: bm25, boolean, or stableTfl.

To learn more about the available similarity algorithms, see Score Details.

bm25

multi

String Field Definition

Optional

String field to index with the name of the alternate analyzer specified in the multi object. To learn more about specifying the multi object, see Multi Analyzer and an example below.

norms

string

Optional

String that specifies whether to include or omit the field length in the result when scoring. The length of the field is determined by the number of tokens produced by the analyzer for the field. Value can be one of the following:

  • include - to include the field length when scoring.

  • omit - to omit the field length when scoring.

If value is include, MongoDB Search uses the length of the field to determine the higher score when scoring. For example, if two documents match a MongoDB Search query, the document with the shorter field length scores higher than the document with the longer field length.

If value is omit, MongoDB Search ignores the field length when scoring.

include

The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the string type.

To learn how to set up and run the following example code, see Define the Index for the token Type.

The following index definition for the sample_mflix.movies collection in the sample dataset indexes the title field with string values.

1from pymongo import MongoClient
2from pymongo.operations import SearchIndexModel
3
4# connect to your Atlas deployment
5uri = "<connection-string>"
6client = MongoClient(uri)
7
8# set namespace
9database = client["sample_mflix"]
10collection = database["movies"]
11
12# define your MongoDB Search index
13search_index_model = SearchIndexModel(
14 definition={
15 "mappings": {
16 "dynamic": False,
17 "fields": {
18 "title": {
19 "type": "string"
20 }
21 }
22 },
23 },
24 name="default",
25)
26
27# create the index
28result = collection.create_search_index(model=search_index_model)
29print(f"New index name: {result}")
Rate this page