Use the MongoDB Search token field type to index string values for sorting, faceting, and querying. After you index a field as token, you can sort and group results by the indexed field, and query it using the equals, in, and range operators.
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Retrieve your Service Account access token for the project.
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.
Make an API call.
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 token field type.
Replace {
ACCESS-TOKEN} with the output from the preceding stepReplace {
groupId} with the project ID of the project where you want to create the MongoDB Search indexReplace {
clusterName} with the name of the cluster where you want to create the MongoDB Search index
1 curl --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 "genres": [ 14 { 15 "type": "string" 16 }, 17 { 18 "type": "token" 19 } 20 ] 21 } 22 } 23 } 24 }'
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 curl --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": "token", 15 "normalizer": "lowercase" 16 } 17 } 18 } 19 } 20 }'
{"collectionName":"comments","database":"sample_mflix","indexID":"687a8d52a3b4982b8c228383","latestDefinition":{"mappings":{"dynamic":true,"fields":{"title":{"normalizer":"lowercase","type":"token"}}}},"latestDefinitionVersion":{"version":0},"name":"default_15","queryable":false,"status":"PENDING","type":"search"}
The following index definition indexes the genres field as string and token types to return the following:
1 curl --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 "genres": [ 14 { 15 "type": "string" 16 }, 17 { 18 "type": "token" 19 } 20 ] 21 } 22 } 23 } 24 }'
{"collectionName":"movies","database":"sample_mflix","indexID":"687a8ce25532743c25aa2d34","latestDefinition":{"mappings":{"dynamic":true,"fields":{"genres":[{"type":"string"},{"type":"token"}]}}},"latestDefinitionVersion":{"version":0},"name":"default_20","queryable":false,"status":"PENDING","type":"search"}
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Create a search-index.json configuration file and specify the token type.
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": "token", 11 "normalizer": "lowercase|none" 12 } 13 } 14 } 15 } 16 }
Connect to the Atlas CLI
In your terminal, connect to your cluster from the Atlas CLI. To learn more, see Connect from the Atlas CLI.
Create a MongoDB Search index.
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>
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 { 2 "name": "default", 3 "collectionName": "movies", 4 "database": "sample_mflix", 5 "definition": { 6 "mappings": { 7 "dynamic": false, 8 "fields": { 9 "title": { 10 "type": "token", 11 "normalizer": "lowercase" 12 } 13 } 14 } 15 } 16 }
The following index definition indexes the genres field as string and token types to return the following:
1 { 2 "name": "default", 3 "collectionName": "movies", 4 "database": "sample_mflix", 5 "definition": { 6 "mappings": { 7 "dynamic": false, 8 "fields": { 9 "genres": [ 10 { 11 "type": "string" 12 }, 13 { 14 "type": "token" 15 } 16 ] 17 } 18 } 19 } 20 }
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Connect to your cluster using MongoDB Compass.
Open Compass and connect to your cluster. For detailed instructions, see Connect to a Cluster via Compass.
Create the MongoDB Search index.
Click the Indexes tab, then select Search Indexes.
Click Create Atlas Search Index to open the index creation dialog box.
Specify a name for the index.
Your MongoDB Search index is named
defaultby 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 differentindexoption in its operators. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.Specify the JSON MongoDB Search index definition.
1 { 2 "mappings": { 3 "dynamic": true|false, 4 "fields": { 5 "<field-name>": { 6 "type": "token", 7 "normalizer": "lowercase|none" 8 } 9 } 10 } 11 } Click Create Search Index.
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 { 2 "mappings": { 3 "dynamic": false, 4 "fields": { 5 "title": { 6 "type": "token", 7 "normalizer": "lowercase" 8 } 9 } 10 } 11 }
The following index definition indexes the genres field as string and token types to return the following:
1 { 2 "mappings": { 3 "dynamic": false, 4 "fields": { 5 "genres": [ 6 { 7 "type": "string" 8 }, 9 { 10 "type": "token" 11 } 12 ] 13 } 14 } 15 }
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Connect to the deployment by using mongosh.
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.
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 db.movies.createSearchIndex( 2 "default", 3 { 4 "mappings": { 5 "dynamic": false, 6 "fields": { 7 "title": { 8 "type": "token", 9 "normalizer": "lowercase" 10 } 11 } 12 } 13 } 14 )
The following index definition indexes the genres field as string and token types to return the following:
1 db.movies.createSearchIndex( 2 "default", 3 { 4 "mappings": { 5 "dynamic": false, 6 "fields": { 7 "genres": [ 8 { 9 "type": "string" 10 }, 11 { 12 "type": "token" 13 } 14 ] 15 } 16 } 17 } 18 )
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Choose your preferred configuration method in the Atlas UI and then select the database and collection.
Click Refine Your Index to configure your index.
In the Field Mappings section, click Add Field Mapping to open the Add Field Mapping window.
Click Customized Configuration.
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.Click the Data Type dropdown and select Token.
Configure the field properties for the
tokentype. To learn more, see Field Properties.Click Add.
The following is the JSON syntax for the token type. Replace the default index definition with the following. To learn more about the fields, see Field Properties.
1 { 2 "mappings": { 3 "dynamic": true|false, 4 "fields": { 5 "<field-name>": { 6 "type": "token", 7 "normalizer": "lowercase|none" 8 } 9 } 10 } 11 }
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 { 2 "mappings": { 3 "dynamic": false, 4 "fields": { 5 "title": { 6 "type": "token", 7 "normalizer": "lowercase" 8 } 9 } 10 } 11 }
The following index definition indexes the genres field as string and token types to return the following:
1 { 2 "mappings": { 3 "dynamic": false, 4 "fields": { 5 "genres": [ 6 { 7 "type": "string" 8 }, 9 { 10 "type": "token" 11 } 12 ] 13 } 14 } 15 }
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Set up the C project.
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 2 mkdir atlas-search-project && cd atlas-search-project
Add the C driver to your project by following the instructions in the MongoDB C Driver documentation.
Define the index.
Create a create_index.c file in your project directory, and copy and paste the following code into the file.
1 2 3 4 int 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": "token", 38 "normalizer": "lowercase|none" 39 } 40 } 41 }, 42 } 43 } ] 44 }); 45 46 // Convert your command to BSON 47 if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) { 48 fprintf(stderr, "Failed to parse command: %s\n", error.message); 49 ok = false; 50 goto cleanup; 51 } 52 53 // Create the MongoDB Search index by running the command 54 if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { 55 fprintf(stderr, "Failed to run createSearchIndexes: %s\n", error.message); 56 ok = false; 57 goto cleanup; 58 } 59 printf ("Index created!\n"); 60 61 cleanup: 62 mongoc_collection_destroy (collection); 63 mongoc_client_destroy (client); 64 mongoc_database_destroy (database); 65 bson_destroy (&cmd); 66 mongoc_cleanup (); 67 return ok ? EXIT_SUCCESS : EXIT_FAILURE; 68 }
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.
Set up a CMake application
To configure your application, create a CMakeLists.txt file in your project directory. Then, add the following code to the file:
1 cmake_minimum_required(VERSION 3.11) 2 project(atlas-search-index LANGUAGES C) 3 add_executable (index.out create_index.c) 4 find_package(mongoc <version> REQUIRED) 5 target_link_libraries(index.out mongoc::mongoc)
The preceding code performs the following actions:
Configures a C project.
Creates a
index.outexecutable for your application.Finds and requires the C driver. Replace the
<version>placeholder with your C driver version token, such as2.0.0.Links the program to the
libmongoclibrary.
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.
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 2 3 4 int 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": "token", 38 "normalizer": "lowercase" 39 } 40 } 41 }, 42 } 43 } ] 44 }); 45 46 // Convert your command to BSON 47 if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) { 48 fprintf(stderr, "Failed to parse command: %s\n", error.message); 49 ok = false; 50 goto cleanup; 51 } 52 53 // Create the MongoDB Search index by running the command 54 if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { 55 fprintf(stderr, "Failed to run createSearchIndexes: %s\n", error.message); 56 ok = false; 57 goto cleanup; 58 } 59 printf ("Index created!\n"); 60 61 cleanup: 62 mongoc_collection_destroy (collection); 63 mongoc_client_destroy (client); 64 mongoc_database_destroy (database); 65 bson_destroy (&cmd); 66 mongoc_cleanup (); 67 return ok ? EXIT_SUCCESS : EXIT_FAILURE; 68 }
The following index definition indexes the genres field as string and token types to return the following:
1 2 3 4 int 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 "genres" : [ 37 { 38 "type": "string" 39 }, 40 { 41 "type": "token" 42 } 43 ] 44 } 45 }, 46 } 47 } ] 48 }); 49 50 // Convert your command to BSON 51 if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) { 52 fprintf(stderr, "Failed to parse command: %s\n", error.message); 53 ok = false; 54 goto cleanup; 55 } 56 57 // Create the MongoDB Search index by running the command 58 if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { 59 fprintf(stderr, "Failed to run createSearchIndexes: %s\n", error.message); 60 ok = false; 61 goto cleanup; 62 } 63 printf ("Index created!\n"); 64 65 cleanup: 66 mongoc_collection_destroy (collection); 67 mongoc_client_destroy (client); 68 mongoc_database_destroy (database); 69 bson_destroy (&cmd); 70 mongoc_cleanup (); 71 return ok ? EXIT_SUCCESS : EXIT_FAILURE; 72 }
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Set up and initialize the .NET/C# project.
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.
Define the index.
Paste the following code into the Program.cs file.
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 4 // connect to your Atlas deployment 5 var uri = "<connection-string>"; 6 7 var client = new MongoClient(uri); 8 9 var db = client.GetDatabase("<database>"); 10 var collection = db.GetCollection<BsonDocument>("<collection>"); 11 12 // define your MongoDB Search index 13 var 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", "token" }, 24 { "normalizer", "lowercase|none" } 25 } 26 } 27 } 28 } 29 } 30 } 31 }); 32 33 var result = collection.SearchIndexes.CreateOne(index); 34 Console.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.
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 4 // connect to your Atlas deployment 5 var uri = "<connection-string>"; 6 7 var client = new MongoClient(uri); 8 9 var db = client.GetDatabase("sample_mflix"); 10 var collection = db.GetCollection<BsonDocument>("movies"); 11 12 // define your MongoDB Search index 13 var 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", "token" }, 24 { "normalizer", "lowercase" } 25 } 26 } 27 } 28 } 29 } 30 } 31 }); 32 33 var result = collection.SearchIndexes.CreateOne(index); 34 Console.WriteLine($"New index name: {result}");
The following index definition indexes the genres field as string and token types to return the following:
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 4 // connect to your Atlas deployment 5 var uri = "<connection-string>"; 6 7 var client = new MongoClient(uri); 8 9 var db = client.GetDatabase("sample_mflix"); 10 var collection = db.GetCollection<BsonDocument>("movies"); 11 12 // define your MongoDB Search index 13 var index = new CreateSearchIndexModel( 14 "default", new BsonDocument 15 { 16 { "mappings", new BsonDocument 17 { 18 { "dynamic", false }, 19 { "fields", new BsonDocument 20 { 21 { "genres", new BsonArray 22 { 23 new BsonDocument 24 { 25 { "type", "string" } 26 }, 27 new BsonDocument 28 { 29 { "type", "token" } 30 } 31 } 32 } 33 } 34 } 35 } 36 } 37 }); 38 39 var result = collection.SearchIndexes.CreateOne(index); 40 Console.WriteLine($"New index name: {result}");
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Set up the C++ project.
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.
Define the index.
Create a CreateIndex.cpp file in your project directory, and copy and paste the following code into the file.
1 2 3 4 5 6 7 8 9 using bsoncxx::builder::basic::kvp; 10 using bsoncxx::builder::basic::make_document; 11 12 13 int 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", "token"), 33 kvp("normalizer", "lowercase|none") 34 )) 35 )) 36 )) 37 ); 38 39 auto model = mongocxx::search_index_model(name, definition.view()); 40 41 // Create the search index 42 auto result = siv.create_one(model); 43 std::cout << "New index name: " << result << std::endl; 44 } 45 }
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.
Create the index.
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
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 2 3 4 5 6 7 8 9 using bsoncxx::builder::basic::kvp; 10 using bsoncxx::builder::basic::make_document; 11 12 13 int 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", "token"), 33 kvp("normalizer", "lowercase") 34 )) 35 )) 36 )) 37 ); 38 39 auto model = mongocxx::search_index_model(name, definition.view()); 40 41 // Create the search index 42 auto result = siv.create_one(model); 43 std::cout << "New index name: " << result << std::endl; 44 } 45 }
The following index definition indexes the genres field as string and token types to return the following:
1 2 3 4 5 6 7 8 9 using bsoncxx::builder::basic::kvp; 10 using bsoncxx::builder::basic::make_document; 11 12 13 int 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("genres", [](bsoncxx::builder::basic::sub_array array) { 32 array.append(make_document( 33 kvp("type", "string") 34 )); 35 array.append(make_document( 36 kvp("type", "token") 37 )); 38 }) 39 )) 40 )) 41 ); 42 43 auto model = mongocxx::search_index_model(name, definition.view()); 44 45 // Create the search index 46 auto result = siv.create_one(model); 47 std::cout << "New index name: " << result << std::endl; 48 } 49 }
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Set up and initialize the Go module.
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 go mod init atlas-search-project Add the MongoDB Go Driver to your project go get go.mongodb.org/mongo-driver/v2/mongo
For more detailed installation instructions, see the MongoDB Go Driver documentation.
Define the index.
Create a create_index.go file in your project directory, and copy and paste the following code into the file.
1 package main 2 3 import ( 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 13 func 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 token 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", "token"}, 40 {"normalizer", "lowercase|none"}, // Optional: specify a normalizer 41 }}, 42 }}, 43 }}, 44 }, 45 Options: opts, 46 } 47 48 // Create the index 49 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel) 50 if err != nil { 51 log.Fatalf("Failed to create the Atlas Search index: %v", err) 52 } 53 54 fmt.Println("Name of index created: " + searchIndexName) 55 }
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
Your connection string should use the following format:
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
IMPORTANT: Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.
Your connection string should use the following format:
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see Connection Strings.
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 package main 2 3 import ( 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 13 func 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 token 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", "token"}, 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 }
The following index definition indexes the genres field as string and token types to return the following:
1 package main 2 3 import ( 4 "context" 5 "log" 6 7 "go.mongodb.org/mongo-driver/v2/bson" 8 "go.mongodb.org/mongo-driver/v2/mongo" 9 "go.mongodb.org/mongo-driver/v2/mongo/options" 10 ) 11 12 func main() { 13 ctx := context.Background() 14 15 // Retrieves your Atlas connection string 16 const uri = "<connection-string>" 17 18 // Connect to your Atlas cluster 19 clientOptions := options.Client().ApplyURI(uri) 20 client, err := mongo.Connect(clientOptions) 21 if err != nil { 22 log.Fatalf("Failed to connect to the server: %v", err) 23 } 24 defer func() { 25 if err := client.Disconnect(ctx); err != nil { 26 log.Fatalf("Failed to disconnect: %v", err) 27 } 28 }() 29 30 // Set the namespace 31 coll := client.Database("sample_mflix").Collection("movies") 32 33 // Define your search index with key-value pairs 34 searchIndexModel := mongo.SearchIndexModel{ 35 Definition: bson.D{ 36 {"mappings", bson.D{ 37 {"dynamic", false}, 38 {"fields", bson.D{ 39 {"genres", bson.A{ 40 bson.D{ 41 {"type", "string"}, 42 }, 43 bson.D{ 44 {"type", "token"}, 45 }, 46 }}, 47 }}, 48 }}, 49 }, 50 Options: opts, 51 } 52 53 // Create the index 54 result, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel) 55 if err != nil { 56 log.Fatalf("Failed to create search index: %v", err) 57 } 58 log.Printf("New index name: %v", result) 59 }
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Set up your Java project with the MongoDB Java driver.
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>
Add the following code to dependencies list in your build.gradle file:
dependencies { implementation(platform("org.mongodb:mongodb-driver-bom:5.5.1")) }
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:
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.11.1</version> </dependency> </dependencies>
Add the following to the dependencies array in your Gradle project's build.gradle file:
dependencies { // MongoDB Java Sync Driver v4.11.0 or later implementation 'org.mongodb:mongodb-driver-sync' }
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.
Define the index.
In your project's base package directory, create a CreateIndex.java file and copy and paste the following code into this file.
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 7 public 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", "token") 21 .append("normalizer", "lowercase|none") 22 ))); 23 24 String result = collection.createSearchIndex(index); 25 System.out.println("New index name: " + result); 26 } 27 } 28 }
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.
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 7 public 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("sample_mflix"); 15 MongoCollection<Document> collection = database.getCollection("movies"); 16 17 Document index = new Document("mappings", 18 new Document("dynamic", false) 19 .append("fields", new Document("title", 20 new Document("type", "token") 21 .append("normalizer", "lowercase") 22 ))); 23 24 String result = collection.createSearchIndex(index); 25 System.out.println("New index name: " + result); 26 } 27 } 28 }
The following index definition indexes the genres field as string and token types to return the following:
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 import java.util.Arrays; 7 8 public class CreateIndex { 9 public static void main(String[] args) { 10 // connect to your Atlas cluster 11 String uri = "<connection-string>"; 12 13 try (MongoClient mongoClient = MongoClients.create(uri)) { 14 // set namespace 15 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 16 MongoCollection<Document> collection = database.getCollection("movies"); 17 18 Document index = new Document("mappings", 19 new Document("dynamic", false) 20 .append("fields", new Document("genres", 21 Arrays.asList( 22 new Document("type", "string"), 23 new Document("type", "token") 24 )))); 25 26 String result = collection.createSearchIndex(index); 27 System.out.println("New index name: " + result); 28 } 29 } 30 }
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Initialize your Node.js project.
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.
Define the index.
Create a create-index.js file in your project directory, and copy and paste the following code into the file.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async 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": "token", 26 "normalizer": "lowercase|none" 27 } 28 } 29 } 30 } 31 } 32 33 // run the helper method 34 const result = await collection.createSearchIndex(index); 35 console.log("New index name: " + result); 36 } finally { 37 await client.close(); 38 } 39 } 40 41 run().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.
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async 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": false, 23 "fields": { 24 "title": { 25 "type": "token", 26 "normalizer": "lowercase" 27 } 28 } 29 } 30 } 31 } 32 33 // run the helper method 34 const result = await collection.createSearchIndex(index); 35 console.log("New index name: " + result); 36 } finally { 37 await client.close(); 38 } 39 } 40 41 run().catch(console.dir);
The following index definition indexes the genres field as string and token types to return the following:
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async 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": false, 23 "fields": { 24 "genres": [ 25 { 26 "type": "string" 27 }, 28 { 29 "type": "token" 30 } 31 ] 32 } 33 } 34 } 35 } 36 37 // run the helper method 38 const result = await collection.createSearchIndex(index); 39 console.log("New index name: " + result); 40 } finally { 41 await client.close(); 42 } 43 } 44 45 run().catch(console.dir);
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Set up the Python project.
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).
Define the index.
Create a create_index.py file in your project directory, and copy and paste the following code into the file.
1 from pymongo import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 # connect to your Atlas deployment 5 uri = "<connection-string>" 6 client = MongoClient(uri) 7 8 # set namespace 9 database = client["<database>"] 10 collection = database["<collection>"] 11 12 # define your MongoDB Search index 13 search_index_model = SearchIndexModel( 14 definition={ 15 "mappings": { 16 "dynamic": true|false, 17 "fields": { 18 "<field_name>":{ 19 "type": "token", 20 "normalizer": "lowercase|none" 21 } 22 } 23 }, 24 }, 25 name="default", 26 ) 27 28 # create the index 29 result = collection.create_search_index(model=search_index_model) 30 print(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.
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 from pymongo import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 # connect to your Atlas deployment 5 uri = "<connection-string>" 6 client = MongoClient(uri) 7 8 # set namespace 9 database = client["sample_mflix"] 10 collection = database["movies"] 11 12 # define your MongoDB Search index 13 search_index_model = SearchIndexModel( 14 definition={ 15 "mappings": { 16 "dynamic": false, 17 "fields": { 18 "title": { 19 "type": "token", 20 "normalizer": "lowercase" 21 } 22 } 23 }, 24 }, 25 name="default", 26 ) 27 28 # create the index 29 result = collection.create_search_index(model=search_index_model) 30 print(f"New index name: {result}")
The following index definition indexes the genres field as string and token types to return the following:
1 from pymongo import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 # connect to your Atlas deployment 5 uri = "<connection-string>" 6 client = MongoClient(uri) 7 8 # set namespace 9 database = client["sample_mflix"] 10 collection = database["movies"] 11 12 # define your MongoDB Search index 13 search_index_model = SearchIndexModel( 14 definition={ 15 "mappings": { 16 "dynamic": False, 17 "fields": { 18 "genres": [ 19 { 20 "type": "string" 21 }, 22 { 23 "type": "token" 24 } 25 ] 26 } 27 }, 28 }, 29 name="default", 30 ) 31 32 # create the index 33 result = collection.create_search_index(model=search_index_model) 34 print(f"New index name: {result}")
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Create a search-index.json configuration file and specify the token type.
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": "token", 11 "normalizer": "lowercase|none" 12 } 13 } 14 } 15 } 16 }
Connect to the Atlas CLI
In your terminal, connect to your local deployment from the Atlas CLI. To learn more, see Connect from the Atlas CLI.
Create a MongoDB Search index.
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>
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 { 2 "name": "default", 3 "collectionName": "movies", 4 "database": "sample_mflix", 5 "definition": { 6 "mappings": { 7 "dynamic": false, 8 "fields": { 9 "title": { 10 "type": "token", 11 "normalizer": "lowercase" 12 } 13 } 14 } 15 } 16 }
The following index definition indexes the genres field as string and token types to return the following:
1 { 2 "name": "default", 3 "collectionName": "movies", 4 "database": "sample_mflix", 5 "definition": { 6 "mappings": { 7 "dynamic": false, 8 "fields": { 9 "genres": [ 10 { 11 "type": "string" 12 }, 13 { 14 "type": "token" 15 } 16 ] 17 } 18 } 19 } 20 }
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Connect to your cluster using MongoDB Compass.
Open Compass and connect to your cluster. For detailed instructions, see Connect to a Cluster via Compass.
Create the MongoDB Search index.
Click the Indexes tab, then select Search Indexes.
Click Create Atlas Search Index to open the index creation dialog box.
Specify a name for the index.
Your MongoDB Search index is named
defaultby 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 differentindexoption in its operators. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.Specify the JSON MongoDB Search index definition.
1 { 2 "mappings": { 3 "dynamic": true|false, 4 "fields": { 5 "<field-name>": { 6 "type": "token", 7 "normalizer": "lowercase|none" 8 } 9 } 10 } 11 } Click Create Search Index.
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 { 2 "mappings": { 3 "dynamic": false, 4 "fields": { 5 "title": { 6 "type": "token", 7 "normalizer": "lowercase" 8 } 9 } 10 } 11 }
The following index definition indexes the genres field as string and token types to return the following:
1 { 2 "mappings": { 3 "dynamic": false, 4 "fields": { 5 "genres": [ 6 { 7 "type": "string" 8 }, 9 { 10 "type": "token" 11 } 12 ] 13 } 14 } 15 }
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Connect to the deployment by using mongosh.
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.
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 db.movies.createSearchIndex( 2 "default", 3 { 4 "mappings": { 5 "dynamic": false, 6 "fields": { 7 "title": { 8 "type": "token", 9 "normalizer": "lowercase" 10 } 11 } 12 } 13 } 14 )
The following index definition indexes the genres field as string and token types to return the following:
1 db.movies.createSearchIndex( 2 "default", 3 { 4 "mappings": { 5 "dynamic": false, 6 "fields": { 7 "genres": [ 8 { 9 "type": "string" 10 }, 11 { 12 "type": "token" 13 } 14 ] 15 } 16 } 17 } 18 )
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Set up the C project.
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 2 mkdir atlas-search-project && cd atlas-search-project
Add the C driver to your project by following the instructions in the MongoDB C Driver documentation.
Define the index.
Create a create_index.c file in your project directory, and copy and paste the following code into the file.
1 2 3 4 int 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": "token", 38 "normalizer": "lowercase|none" 39 } 40 } 41 }, 42 } 43 } ] 44 }); 45 46 // Convert your command to BSON 47 if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) { 48 fprintf(stderr, "Failed to parse command: %s\n", error.message); 49 ok = false; 50 goto cleanup; 51 } 52 53 // Create the MongoDB Search index by running the command 54 if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { 55 fprintf(stderr, "Failed to run createSearchIndexes: %s\n", error.message); 56 ok = false; 57 goto cleanup; 58 } 59 printf ("Index created!\n"); 60 61 cleanup: 62 mongoc_collection_destroy (collection); 63 mongoc_client_destroy (client); 64 mongoc_database_destroy (database); 65 bson_destroy (&cmd); 66 mongoc_cleanup (); 67 return ok ? EXIT_SUCCESS : EXIT_FAILURE; 68 }
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.
Set up a CMake application
To configure your application, create a CMakeLists.txt file in your project directory. Then, add the following code to the file:
1 cmake_minimum_required(VERSION 3.11) 2 project(atlas-search-index LANGUAGES C) 3 add_executable (index.out create_index.c) 4 find_package(mongoc <version> REQUIRED) 5 target_link_libraries(index.out mongoc::mongoc)
The preceding code performs the following actions:
Configures a C project.
Creates a
index.outexecutable for your application.Finds and requires the C driver. Replace the
<version>placeholder with your C driver version token, such as2.0.0.Links the program to the
libmongoclibrary.
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.
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 2 3 4 int 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": "token", 38 "normalizer": "lowercase" 39 } 40 } 41 }, 42 } 43 } ] 44 }); 45 46 // Convert your command to BSON 47 if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) { 48 fprintf(stderr, "Failed to parse command: %s\n", error.message); 49 ok = false; 50 goto cleanup; 51 } 52 53 // Create the MongoDB Search index by running the command 54 if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { 55 fprintf(stderr, "Failed to run createSearchIndexes: %s\n", error.message); 56 ok = false; 57 goto cleanup; 58 } 59 printf ("Index created!\n"); 60 61 cleanup: 62 mongoc_collection_destroy (collection); 63 mongoc_client_destroy (client); 64 mongoc_database_destroy (database); 65 bson_destroy (&cmd); 66 mongoc_cleanup (); 67 return ok ? EXIT_SUCCESS : EXIT_FAILURE; 68 }
The following index definition indexes the genres field as string and token types to return the following:
1 2 3 4 int 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 "genres" : [ 37 { 38 "type": "string" 39 }, 40 { 41 "type": "token" 42 } 43 ] 44 } 45 }, 46 } 47 } ] 48 }); 49 50 // Convert your command to BSON 51 if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) { 52 fprintf(stderr, "Failed to parse command: %s\n", error.message); 53 ok = false; 54 goto cleanup; 55 } 56 57 // Create the MongoDB Search index by running the command 58 if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { 59 fprintf(stderr, "Failed to run createSearchIndexes: %s\n", error.message); 60 ok = false; 61 goto cleanup; 62 } 63 printf ("Index created!\n"); 64 65 cleanup: 66 mongoc_collection_destroy (collection); 67 mongoc_client_destroy (client); 68 mongoc_database_destroy (database); 69 bson_destroy (&cmd); 70 mongoc_cleanup (); 71 return ok ? EXIT_SUCCESS : EXIT_FAILURE; 72 }
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Set up and initialize the .NET/C# project.
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.
Define the index.
Paste the following code into the Program.cs file.
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 4 // connect to your Atlas deployment 5 var uri = "<connection-string>"; 6 7 var client = new MongoClient(uri); 8 9 var db = client.GetDatabase("<database>"); 10 var collection = db.GetCollection<BsonDocument>("<collection>"); 11 12 // define your MongoDB Search index 13 var 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", "token" }, 24 { "normalizer", "lowercase|none" } 25 } 26 } 27 } 28 } 29 } 30 } 31 }); 32 33 var result = collection.SearchIndexes.CreateOne(index); 34 Console.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.
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 4 // connect to your Atlas deployment 5 var uri = "<connection-string>"; 6 7 var client = new MongoClient(uri); 8 9 var db = client.GetDatabase("sample_mflix"); 10 var collection = db.GetCollection<BsonDocument>("movies"); 11 12 // define your MongoDB Search index 13 var 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", "token" }, 24 { "normalizer", "lowercase" } 25 } 26 } 27 } 28 } 29 } 30 } 31 }); 32 33 var result = collection.SearchIndexes.CreateOne(index); 34 Console.WriteLine($"New index name: {result}");
The following index definition indexes the genres field as string and token types to return the following:
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 4 // connect to your Atlas deployment 5 var uri = "<connection-string>"; 6 7 var client = new MongoClient(uri); 8 9 var db = client.GetDatabase("sample_mflix"); 10 var collection = db.GetCollection<BsonDocument>("movies"); 11 12 // define your MongoDB Search index 13 var index = new CreateSearchIndexModel( 14 "default", new BsonDocument 15 { 16 { "mappings", new BsonDocument 17 { 18 { "dynamic", false }, 19 { "fields", new BsonDocument 20 { 21 { "genres", new BsonArray 22 { 23 new BsonDocument 24 { 25 { "type", "string" } 26 }, 27 new BsonDocument 28 { 29 { "type", "token" } 30 } 31 } 32 } 33 } 34 } 35 } 36 } 37 }); 38 39 var result = collection.SearchIndexes.CreateOne(index); 40 Console.WriteLine($"New index name: {result}");
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Set up the C++ project.
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.
Define the index.
Create a CreateIndex.cpp file in your project directory, and copy and paste the following code into the file.
1 2 3 4 5 6 7 8 9 using bsoncxx::builder::basic::kvp; 10 using bsoncxx::builder::basic::make_document; 11 12 13 int 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", "token"), 33 kvp("normalizer", "lowercase|none") 34 )) 35 )) 36 )) 37 ); 38 39 auto model = mongocxx::search_index_model(name, definition.view()); 40 41 // Create the search index 42 auto result = siv.create_one(model); 43 std::cout << "New index name: " << result << std::endl; 44 } 45 }
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.
Create the index.
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
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 2 3 4 5 6 7 8 9 using bsoncxx::builder::basic::kvp; 10 using bsoncxx::builder::basic::make_document; 11 12 13 int 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", "token"), 33 kvp("normalizer", "lowercase") 34 )) 35 )) 36 )) 37 ); 38 39 auto model = mongocxx::search_index_model(name, definition.view()); 40 41 // Create the search index 42 auto result = siv.create_one(model); 43 std::cout << "New index name: " << result << std::endl; 44 } 45 }
The following index definition indexes the genres field as string and token types to return the following:
1 2 3 4 5 6 7 8 9 using bsoncxx::builder::basic::kvp; 10 using bsoncxx::builder::basic::make_document; 11 12 13 int 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("genres", [](bsoncxx::builder::basic::sub_array array) { 32 array.append(make_document( 33 kvp("type", "string") 34 )); 35 array.append(make_document( 36 kvp("type", "token") 37 )); 38 }) 39 )) 40 )) 41 ); 42 43 auto model = mongocxx::search_index_model(name, definition.view()); 44 45 // Create the search index 46 auto result = siv.create_one(model); 47 std::cout << "New index name: " << result << std::endl; 48 } 49 }
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Set up and initialize the Go module.
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 go mod init atlas-search-project Add the MongoDB Go Driver to your project go get go.mongodb.org/mongo-driver/v2/mongo
For more detailed installation instructions, see the MongoDB Go Driver documentation.
Define the index.
Create a create_index.go file in your project directory, and copy and paste the following code into the file.
1 package main 2 3 import ( 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 13 func 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 token 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", "token"}, 40 {"normalizer", "lowercase|none"}, // Optional: specify a normalizer 41 }}, 42 }}, 43 }}, 44 }, 45 Options: opts, 46 } 47 48 // Create the index 49 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel) 50 if err != nil { 51 log.Fatalf("Failed to create the Atlas Search index: %v", err) 52 } 53 54 fmt.Println("Name of index created: " + searchIndexName) 55 }
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
Your connection string should use the following format:
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
IMPORTANT: Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.
Your connection string should use the following format:
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see Connection Strings.
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 package main 2 3 import ( 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 13 func 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 token 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", "token"}, 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 }
The following index definition indexes the genres field as string and token types to return the following:
1 package main 2 3 import ( 4 "context" 5 "log" 6 7 "go.mongodb.org/mongo-driver/v2/bson" 8 "go.mongodb.org/mongo-driver/v2/mongo" 9 "go.mongodb.org/mongo-driver/v2/mongo/options" 10 ) 11 12 func main() { 13 ctx := context.Background() 14 15 // Retrieves your Atlas connection string 16 const uri = "<connection-string>" 17 18 // Connect to your Atlas cluster 19 clientOptions := options.Client().ApplyURI(uri) 20 client, err := mongo.Connect(clientOptions) 21 if err != nil { 22 log.Fatalf("Failed to connect to the server: %v", err) 23 } 24 defer func() { 25 if err := client.Disconnect(ctx); err != nil { 26 log.Fatalf("Failed to disconnect: %v", err) 27 } 28 }() 29 30 // Set the namespace 31 coll := client.Database("sample_mflix").Collection("movies") 32 33 // Define your search index with key-value pairs 34 searchIndexModel := mongo.SearchIndexModel{ 35 Definition: bson.D{ 36 {"mappings", bson.D{ 37 {"dynamic", false}, 38 {"fields", bson.D{ 39 {"genres", bson.A{ 40 bson.D{ 41 {"type", "string"}, 42 }, 43 bson.D{ 44 {"type", "token"}, 45 }, 46 }}, 47 }}, 48 }}, 49 }, 50 Options: opts, 51 } 52 53 // Create the index 54 result, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel) 55 if err != nil { 56 log.Fatalf("Failed to create search index: %v", err) 57 } 58 log.Printf("New index name: %v", result) 59 }
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Set up your Java project with the MongoDB Java driver.
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>
Add the following code to dependencies list in your build.gradle file:
dependencies { implementation(platform("org.mongodb:mongodb-driver-bom:5.5.1")) }
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:
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.11.1</version> </dependency> </dependencies>
Add the following to the dependencies array in your Gradle project's build.gradle file:
dependencies { // MongoDB Java Sync Driver v4.11.0 or later implementation 'org.mongodb:mongodb-driver-sync' }
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.
Define the index.
In your project's base package directory, create a CreateIndex.java file and copy and paste the following code into this file.
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 7 public 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", "token") 21 .append("normalizer", "lowercase|none") 22 ))); 23 24 String result = collection.createSearchIndex(index); 25 System.out.println("New index name: " + result); 26 } 27 } 28 }
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.
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 7 public 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("sample_mflix"); 15 MongoCollection<Document> collection = database.getCollection("movies"); 16 17 Document index = new Document("mappings", 18 new Document("dynamic", false) 19 .append("fields", new Document("title", 20 new Document("type", "token") 21 .append("normalizer", "lowercase") 22 ))); 23 24 String result = collection.createSearchIndex(index); 25 System.out.println("New index name: " + result); 26 } 27 } 28 }
The following index definition indexes the genres field as string and token types to return the following:
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 import java.util.Arrays; 7 8 public class CreateIndex { 9 public static void main(String[] args) { 10 // connect to your Atlas cluster 11 String uri = "<connection-string>"; 12 13 try (MongoClient mongoClient = MongoClients.create(uri)) { 14 // set namespace 15 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 16 MongoCollection<Document> collection = database.getCollection("movies"); 17 18 Document index = new Document("mappings", 19 new Document("dynamic", false) 20 .append("fields", new Document("genres", 21 Arrays.asList( 22 new Document("type", "string"), 23 new Document("type", "token") 24 )))); 25 26 String result = collection.createSearchIndex(index); 27 System.out.println("New index name: " + result); 28 } 29 } 30 }
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Initialize your Node.js project.
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.
Define the index.
Create a create-index.js file in your project directory, and copy and paste the following code into the file.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async 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": "token", 26 "normalizer": "lowercase|none" 27 } 28 } 29 } 30 } 31 } 32 33 // run the helper method 34 const result = await collection.createSearchIndex(index); 35 console.log("New index name: " + result); 36 } finally { 37 await client.close(); 38 } 39 } 40 41 run().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.
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async 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": false, 23 "fields": { 24 "title": { 25 "type": "token", 26 "normalizer": "lowercase" 27 } 28 } 29 } 30 } 31 } 32 33 // run the helper method 34 const result = await collection.createSearchIndex(index); 35 console.log("New index name: " + result); 36 } finally { 37 await client.close(); 38 } 39 } 40 41 run().catch(console.dir);
The following index definition indexes the genres field as string and token types to return the following:
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async 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": false, 23 "fields": { 24 "genres": [ 25 { 26 "type": "string" 27 }, 28 { 29 "type": "token" 30 } 31 ] 32 } 33 } 34 } 35 } 36 37 // run the helper method 38 const result = await collection.createSearchIndex(index); 39 console.log("New index name: " + result); 40 } finally { 41 await client.close(); 42 } 43 } 44 45 run().catch(console.dir);
You must use the MongoDB Search token type to index string fields to enable sorting and faceting on these fields. Then, you can perform the following actions:
Use the
sortoption in your query to sort the results by the indexed field. To learn more, see Sort MongoDB Search Results.Use the
facetcollector in your query to group the results by the indexed field. To learn more, see How to Use Facets with MongoDB Search.
Additionally, you must index string fields as the token type in order to use the equals, in and range operators. To learn more, see the documentation for each respective operator.
Note
You can also use the token type to index string fields for pre-filtering your data for $vectorSearch queries. To learn more, see MongoDB Vector Search Overview.
token Type Limitations
When you index a field as the token type, you must index that field as string type also to query the text value using operators such as text, phrase, etc. For the following operators, you don't need to index the field as string type also to query the text value in the field:
Note
We do not recommend indexing a field with both the stringFacet (deprecated) and token types, unless you require a different normalizer for the token type for a use case other than faceting. With this index definition, MongoDB Search uses the stringFacet definition for faceting.
Review the Behavior of the token Type
When you index a field as token type, MongoDB Search indexes the terms in the string as a single token (searchable term) and stores them in a columnar storage for efficient filtering or sort operations. You can use a normalizer to transform the token. By default, the normalizer is set to none and so MongoDB Search indexes strings in their original form.
The major difference between the MongoDB Search string and token types is that MongoDB Search creates one or more tokens for fields indexed as string type whereas MongoDB Search creates only a single token for fields indexed as the token type.
If a string being indexed as a token field type exceeds 8181 characters, MongoDB Search truncates it to 8181 characters before indexing.
Define the Index for the token Type
Set up the Python project.
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).
Define the index.
Create a create_index.py file in your project directory, and copy and paste the following code into the file.
1 from pymongo import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 # connect to your Atlas deployment 5 uri = "<connection-string>" 6 client = MongoClient(uri) 7 8 # set namespace 9 database = client["<database>"] 10 collection = database["<collection>"] 11 12 # define your MongoDB Search index 13 search_index_model = SearchIndexModel( 14 definition={ 15 "mappings": { 16 "dynamic": true|false, 17 "fields": { 18 "<field_name>":{ 19 "type": "token", 20 "normalizer": "lowercase|none" 21 } 22 } 23 }, 24 }, 25 name="default", 26 ) 27 28 # create the index 29 result = collection.create_search_index(model=search_index_model) 30 print(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.
Configure token Field Properties
The MongoDB Search token type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. Value must be | |
| string | Optional | Type of transformation to perform on the field value. Value can be one of the following:
If you don't set this option explicitly, it defaults to |
|
Try an Example for the token Type
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 token 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 indexes string values in the title field as MongoDB Search token type and converts the field value to lowercase, which allows you to do the following:
Perform case-insensitive sort, as specified by the
normalizer, on thetitlefield.
1 from pymongo import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 # connect to your Atlas deployment 5 uri = "<connection-string>" 6 client = MongoClient(uri) 7 8 # set namespace 9 database = client["sample_mflix"] 10 collection = database["movies"] 11 12 # define your MongoDB Search index 13 search_index_model = SearchIndexModel( 14 definition={ 15 "mappings": { 16 "dynamic": false, 17 "fields": { 18 "title": { 19 "type": "token", 20 "normalizer": "lowercase" 21 } 22 } 23 }, 24 }, 25 name="default", 26 ) 27 28 # create the index 29 result = collection.create_search_index(model=search_index_model) 30 print(f"New index name: {result}")
The following index definition indexes the genres field as string and token types to return the following:
1 from pymongo import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 # connect to your Atlas deployment 5 uri = "<connection-string>" 6 client = MongoClient(uri) 7 8 # set namespace 9 database = client["sample_mflix"] 10 collection = database["movies"] 11 12 # define your MongoDB Search index 13 search_index_model = SearchIndexModel( 14 definition={ 15 "mappings": { 16 "dynamic": False, 17 "fields": { 18 "genres": [ 19 { 20 "type": "string" 21 }, 22 { 23 "type": "token" 24 } 25 ] 26 } 27 }, 28 }, 29 name="default", 30 ) 31 32 # create the index 33 result = collection.create_search_index(model=search_index_model) 34 print(f"New index name: {result}")