The synonyms option in a MongoDB Search index definition specifies synonym mappings that allow you to index and search your collection for words that have the same or nearly the same meaning. To configure a MongoDB Search index with synonym mappings, you must:
Add a collection of synonym documents to your cluster. Ensure that:
Your collection is in the same database as the index that will reference the collection
The documents are properly formatted
Reference the synonym source collection in a synonym mapping in the index definition.
A synonym mapping configures a MongoDB Search index to support queries that apply synonyms from a synonym source collection in the same database as the collection you are indexing. You can use synonyms only in queries that use the text or phrase operator.
This page describes the format of the synonyms source collection and how to define synonym mappings that reference the synonym source collection in your MongoDB Search index.
Syntax
synonyms has the following syntax in an index definition:
1 { 2 "synonyms": [ 3 { 4 "name": "<synonym-mapping-name>", 5 "source": { 6 "collection": "<source-collection-name>" 7 }, 8 "analyzer": "<synonym-mapping-analyzer>" 9 } 10 ] 11 }
Options
synonyms takes the following fields in an index definition:
Field | Type | Description | Necessity |
|---|---|---|---|
| string | Name of the analyzer to use with this synonym mapping. You can use a synonym mapping to query only fields analyzed with the same analyzer. To use synonyms with stop words, you must either index the field using the Standard Analyzer or add the synonym entry without the stop word. You can use any MongoDB Search analyzer except the following:
Custom analyzer tokenizers and token filters:
| Required |
| string | Name of the synonym mapping. Name must be unique in the index definition. Value can't be an empty string. | Required |
| document | Source collection for synonyms. The | Required |
| string | Name of the MongoDB collection that is in the same database as the MongoDB Search index. Documents in this collection must be in the format described in the Synonyms Source Collection Documents. | Required |
Synonyms Source Collection Documents
Each document in the collection specified as the source for the synonyms describe how one or more words map to one or more synonyms of those words.
Note
On free clusters, the synonyms collection can't exceed 10,000 documents.
Format of Synonyms Source Collection Documents
You must configure each document with the following fields:
Field | Type | Description | Necessity |
|---|---|---|---|
| array of strings | Required for For | Conditional |
| string | Type of mapping. Value can be one of the following: | Required |
| array of strings | Words that are synonyms of one another if To use synonyms with stop words, you must either add the synonym entry without the stop word or index the field using the Standard Analyzer. For an example of each | Required |
The documents in the collection can contain other fields. The documents in the collection are additive, and mappings are deduplicated. MongoDB Search synonyms are stored as a separate Atlas collection, which counts against the same storage quota as any other collection in Atlas. MongoDB Search might use more compute resources to apply synonyms from larger synonyms source collections.
Warning
Don't include invalid synonym documents in the synonym source collection. MongoDB Search doesn't create indexes if the indexes use synonym mappings that reference collections with invalid documents. Only include synonym documents that are properly formatted in your synonym source collection.
MongoDB doesn't recommend adding synonym documents to synonym source collections in a production environment without first validating that they are properly formatted and behave as expected in a test environment.
Changes to Synonyms Source Collection Documents
If you make changes to your synonyms source collection:
You don't need to reindex because MongoDB Search watches for changes and automatically updates its internal synonym map.
The time it takes MongoDB Search to update the synonym mappings increases with the synonym source collection size. Note that the changes to synonym documents are reflected in your MongoDB Search query results eventually.
Collection Document Examples
Source Collection Document Examples
Atlas provides the documents for the following MongoDB Search mapping type examples in a collection named sample_synonyms. You can load these documents on your cluster in the same database as your collection. To load these documents on your cluster, when you create the index for your collection, do the following:
When you select the Configuration Method, select the Visual Editor.
When you Add synonym mapping to your index, select Load sample collection from the Synonym source collection dropdown.
equivalent mappingType
In the following example source collection document, the mappingType is set to equivalent so that the tokens car, vehicle, and automobile are configured to be synonyms of one another.
{ "mappingType": "equivalent", "synonyms": ["car", "vehicle", "automobile"] }
For a text query for car, vehicle, or automobile applying a synonym mapping that includes such a document, MongoDB Search returns documents that contain the term car, vehicle, or automobile.
explicit mappingType
In the following example source collection document, mappingType is set to explicit so that the tokens beer, brew, and pint are configured to be synonyms of the input token beer.
{ "mappingType": "explicit", "input": ["beer"], "synonyms": ["beer", "brew", "pint"] }
For a text query for beer applying a synonym mapping that includes such a document, MongoDB Search returns documents that contain the terms "beer", "brew", or "pint" because the input token beer is explicitly mapped to all these synonyms tokens. However, for a query for pint, MongoDB Search does not find documents that contain beer because pint is not explicitly mapped to beer.
Synonym Source Collection Example
The following collection named synonymous_terms is an example synonym source collection that can be used with the movies collection in the sample_mflix database.
The sample_mflix.synonymous_terms collection contains the following documents:
{ "mappingType": "equivalent", "synonyms": ["car", "vehicle", "automobile"] }
{ "mappingType": "explicit", "input": ["race"], "synonyms": ["contest", "rally"] }
{ "mappingType": "equivalent", "synonyms": ["dress", "apparel", "attire"] }
{ "mappingType": "explicit", "input": ["boat"], "synonyms": ["vessel", "sail"] }
Index Definition Examples
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
You can use the Atlas Administration API to configure the index. Replace the following values in the sample curl command:
Replace {
ACCESS-TOKEN} with your Service Account access token. To learn how to generate an access token, see Make an API (Application Programming Interface) Request.Replace {
groupId} with the project ID of the project where you want to create the MongoDB Search index.Replace {
clusterName} with the name of the cluster where you want to create the MongoDB Search index.
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 "plot": { 14 "type": "string", 15 "analyzer": "lucene.english" 16 } 17 } 18 }, 19 "synonyms": [ 20 { 21 "analyzer": "lucene.english", 22 "name": "my_synonyms", 23 "source": { 24 "collection": "synonymous_terms" 25 } 26 } 27 ] 28 } 29 }'
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
You can use the Atlas Administration API to configure the index. Replace the following values in the sample curl command:
Replace {
ACCESS-TOKEN} with your Service Account access token. To learn how to generate an access token, see Make an API (Application Programming Interface) Request.Replace {
groupId} with the project ID of the project where you want to create the MongoDB Search index.Replace {
clusterName} with the name of the cluster where you want to create the MongoDB Search index.
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": true 12 }, 13 "synonyms": [ 14 { 15 "analyzer": "lucene.standard", 16 "name": "my_synonyms", 17 "source": { 18 "collection": "synonymous_terms" 19 } 20 } 21 ] 22 } 23 }'
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
Create a static-index.json configuration file and specify the synonyms field.
1 { 2 "name": "default", 3 "collectionName": "movies", 4 "database": "sample_mflix", 5 "mappings": { 6 "dynamic": false, 7 "fields": { 8 "plot": { 9 "type": "string", 10 "analyzer": "lucene.english" 11 } 12 } 13 }, 14 "synonyms": [ 15 { 16 "analyzer": "lucene.english", 17 "name": "my_synonyms", 18 "source": { 19 "collection": "synonymous_terms" 20 } 21 } 22 ] 23 }
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 static-index.json file:
1 atlas clusters search indexes create <clusterName> --file <path-to-file>
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
Create a dynamic-index.json configuration file and specify the synonyms field.
1 { 2 "name": "default", 3 "collectionName": "movies", 4 "database": "sample_mflix", 5 "mappings": { 6 "dynamic": true 7 }, 8 "synonyms": [ 9 { 10 "analyzer": "lucene.standard", 11 "name": "my_synonyms", 12 "source": { 13 "collection": "synonymous_terms" 14 } 15 } 16 ] 17 }
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 dynamic-index.json file:
1 atlas clusters search indexes create <clusterName> --file <path-to-file>
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
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": false, 4 "fields": { 5 "plot": { 6 "type": "string", 7 "analyzer": "lucene.english" 8 } 9 } 10 }, 11 "synonyms": [ 12 { 13 "analyzer": "lucene.english", 14 "name": "my_synonyms", 15 "source": { 16 "collection": "synonymous_terms" 17 } 18 } 19 ] 20 } Click Create Search Index.
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
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 4 }, 5 "synonyms": [ 6 { 7 "analyzer": "lucene.standard", 8 "name": "my_synonyms", 9 "source": { 10 "collection": "synonymous_terms" 11 } 12 } 13 ] 14 } Click Create Search Index.
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
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.
Run the db.collection.createSearchIndex() method to create the index.
1 db.movies.createSearchIndex( 2 "default", 3 { 4 "mappings": { 5 "dynamic": false, 6 "fields": { 7 "plot": { 8 "type": "string", 9 "analyzer": "lucene.english" 10 } 11 } 12 }, 13 "synonyms": [ 14 { 15 "analyzer": "lucene.english", 16 "name": "my_synonyms", 17 "source": { 18 "collection": "synonymous_terms" 19 } 20 } 21 ]} 22 )
default
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
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.
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
You can use the Visual Editor or the JSON Editor in the Atlas UI to configure the following index. To configure this index, after you select your configuration method, select the movies collection in the sample_mflix database.
Click Refine Your Index.
In the Field Mappings section, click Add Field.
Click Customized Configuration.
Configure the following settings in the Add Field Mapping window:
Field NameEnable Dynamic MappingData Type ConfigurationSelect
plot.Toggle to disable.
Click Add Data Type.
Select String from the dropdown.
Select
lucene.englishunderlucene.languagefrom the Index Analyzer dropdown.
Click Add.
In the Synonyms Mappings section, click Add Synonym Mapping.
Configure the following settings in the Add Synonym Mapping window:
Synonym mapping nameSynonym source collectionAnalyzerEnter
my_synonymsSelect
synonymous_terms.Select
lucene.englishunderlucene.languagefrom dropdown.Click Add.
Replace the default index with the following index.
{ "mappings": { "dynamic": false, "fields": { "plot": { "type": "string", "analyzer": "lucene.english" } } }, "synonyms": [ { "analyzer": "lucene.english", "name": "my_synonyms", "source": { "collection": "synonymous_terms" } } ] }
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
You can use the Visual Editor or the JSON Editor in the Atlas UI to configure the following index. To configure this index, after you select your configuration method, select the movies collection in the sample_mflix database.
Click Refine Your Index.
In the Synonyms Mappings section, click Add Synonym Mapping.
Configure the following settings in the Add Synonym Mapping window:
Synonym mapping nameSynonym source collectionAnalyzerEnter
my_synonymsSelect
synonymous_terms.Select
lucene.standardfrom the dropdown if it isn't already selected.Click Add.
{ "mappings": { "dynamic": true }, "synonyms": [ { "analyzer": "lucene.standard", "name": "my_synonyms", "source": { "collection": "synonymous_terms" } } ] }
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
Set up your application.
To learn how to install the driver and configure your C application, see the Get Started tutorial in the MongoDB C Driver documentation.
Define the index.
Create a create-static-index.c file in your application directory, and copy and paste the following code into the file.
1 2 3 4 int main(int argc, char *argv[]) { 5 mongoc_client_t *client; 6 mongoc_collection_t *collection; 7 bson_error_t error; 8 bson_t cmd; 9 bson_t *index_definition; 10 bool success; 11 12 /* Initialize the MongoDB C Driver. */ 13 mongoc_init(); 14 15 /* Connect to your MongoDB deployment. */ 16 client = mongoc_client_new("<connection-string>"); 17 collection = mongoc_client_get_collection (client, "sample_mflix", "movies"); 18 19 if (!client) { 20 fprintf(stderr, "Failed to create client.\n"); 21 return 1; 22 } 23 24 /* Create the MongoDB Search index definition for the plot field with synonyms. */ 25 char *cmd_str = bson_strdup_printf ( 26 BSON_STR ({ 27 "createSearchIndexes": "%s", 28 "indexes": [{ 29 "name": "default", 30 "definition": { 31 "mappings": { 32 "dynamic": false, 33 "fields": { 34 "plot": { 35 "type": "string", 36 "analyzer": "lucene.english" 37 } 38 } 39 }, 40 "synonyms": [ 41 { 42 "analyzer": "lucene.english", 43 "name": "my_synonyms", 44 "source": { 45 "collection": "synonymous_terms" 46 } 47 } 48 ] 49 } 50 }] 51 }), 52 "movies" 53 ); 54 bson_init_from_json (&cmd, cmd_str, -1, &error); 55 bson_free (cmd_str); 56 57 if (mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { 58 printf ("Index created!\n"); 59 } else { 60 fprintf (stderr, "Failed to create search index: %s", error.message); 61 } 62 63 /* Clean up. */ 64 bson_destroy (&cmd); 65 mongoc_collection_destroy (collection); 66 mongoc_client_destroy(client); 67 mongoc_cleanup(); 68 69 return 0; 70 }
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
Set up your application.
To learn how to install the driver and configure your C application, see the Get Started tutorial in the MongoDB C Driver documentation.
Define the index.
Create a create-dynamic-index.c file in your application directory, and copy and paste the following code into the file.
1 2 3 4 int main(int argc, char *argv[]) { 5 mongoc_client_t *client; 6 mongoc_collection_t *collection; 7 bson_error_t error; 8 bson_t cmd; 9 bson_t *index_definition; 10 bool success; 11 12 /* Initialize the MongoDB C Driver. */ 13 mongoc_init(); 14 15 /* Connect to your MongoDB deployment. */ 16 client = mongoc_client_new("<connection-string>"); 17 collection = mongoc_client_get_collection (client, "sample_mflix", "movies"); 18 19 if (!client) { 20 fprintf(stderr, "Failed to create client.\n"); 21 return 1; 22 } 23 24 /* Create the MongoDB Search index definition for a dynamic index with synonyms. */ 25 char *cmd_str = bson_strdup_printf ( 26 BSON_STR ({ 27 "createSearchIndexes": "%s", 28 "indexes": [{ 29 "name": "default", 30 "definition": { 31 "mappings": { 32 "dynamic": true 33 }, 34 "synonyms": [ 35 { 36 "analyzer": "lucene.standard", 37 "name": "my_synonyms", 38 "source": { 39 "collection": "synonymous_terms" 40 } 41 } 42 ] 43 } 44 }] 45 }), 46 "movies" 47 ); 48 bson_init_from_json (&cmd, cmd_str, -1, &error); 49 bson_free (cmd_str); 50 51 if (mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { 52 printf ("Index created!\n"); 53 } else { 54 fprintf (stderr, "Failed to create search index: %s", error.message); 55 } 56 57 /* Clean up. */ 58 bson_destroy (&cmd); 59 mongoc_collection_destroy (collection); 60 mongoc_client_destroy(client); 61 mongoc_cleanup(); 62 63 return 0; 64 }
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
Set up your application
To learn how to install the driver and configure your C++ application, see the Get Started tutorial in the MongoDB C++ Driver documentation.
Define the index.
Create a CreateStaticIndex.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 int main() { 13 // Initialize the MongoDB C++ driver 14 mongocxx::instance instance{}; 15 16 // Connect to your MongoDB deployment 17 mongocxx::uri uri("<connection-string>"); 18 mongocxx::client client(uri); 19 20 auto db = client["sample_mflix"]; 21 auto collection = db["movies"]; 22 auto siv = collection.search_indexes(); 23 24 // Create the MongoDB Search index definition for the plot field with synonyms 25 auto name = "default"; 26 auto synonyms = bsoncxx::builder::basic::make_array( 27 make_document( 28 kvp("analyzer", "lucene.english"), 29 kvp("name", "my_synonyms"), 30 kvp("source", make_document( 31 kvp("collection", "synonymous_terms") 32 )) 33 ) 34 ); 35 36 auto definition = make_document( 37 kvp("mappings", make_document( 38 kvp("dynamic", false), 39 kvp("fields", make_document( 40 kvp("plot", make_document( 41 kvp("type", "string"), 42 kvp("analyzer", "lucene.english") 43 )) 44 )) 45 )), 46 kvp("synonyms", synonyms) 47 ); 48 auto model = mongocxx::search_index_model(name, definition.view()); 49 50 try { 51 // Execute the command to create the index 52 auto result = siv.create_one(model); 53 std::cout << "New index name: " << result << std::endl; 54 } catch (const std::exception& e) { 55 std::cerr << "Error creating Atlas Search index: " << e.what() << std::endl; 56 } 57 58 }
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
Set up your application
To learn how to install the driver and configure your C++ application, see the Get Started tutorial in the MongoDB C++ Driver documentation.
Define the index.
Create a CreateDynamicIndex.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 int main() { 13 // Initialize the MongoDB C++ driver 14 mongocxx::instance instance{}; 15 16 // Connect to your MongoDB deployment 17 mongocxx::uri uri("<connection-string>"); 18 mongocxx::client client(uri); 19 20 auto db = client["sample_mflix"]; 21 auto collection = db["movies"]; 22 auto siv = collection.search_indexes(); 23 24 // Define the synonym mapping for the lucene.standard analyzer 25 auto name = "default"; 26 auto synonyms = bsoncxx::builder::basic::make_array( 27 make_document( 28 kvp("analyzer", "lucene.standard"), 29 kvp("name", "my_synonyms"), 30 kvp("source", make_document( 31 kvp("collection", "synonymous_terms") 32 )) 33 ) 34 ); 35 36 // Create the MongoDB Search index definition 37 auto definition = make_document( 38 kvp("mappings", make_document( 39 kvp("dynamic", true)) 40 ), 41 kvp("synonyms", synonyms) 42 ); 43 auto model = mongocxx::search_index_model(name, definition.view()); 44 45 try { 46 // Execute the command to create the index 47 auto result = siv.create_one(model); 48 std::cout << "New index name: " << result << std::endl; 49 } catch (const std::exception& e) { 50 std::cerr << "Error creating Atlas Search index: " << e.what() << std::endl; 51 } 52 53 }
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
Set up your application.
To learn how to install the driver and configure your Go application, see the Get Started tutorial in the MongoDB Go Driver documentation.
Define the index.
Create a create-static-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 16 // Replace the placeholder with your MongoDB deployment's connection string 17 uri := "<connection-string>" 18 client, err := mongo.Connect(options.Client(). 19 ApplyURI(uri)) 20 if err != nil { 21 panic(err) 22 } 23 24 defer func() { 25 if err := client.Disconnect(context.TODO()); err != nil { 26 panic(err) 27 } 28 }() 29 30 coll := client.Database("sample_mflix").Collection("movies") 31 const indexName = "default" 32 opts := options.SearchIndexes().SetName(indexName).SetType("search") 33 34 // Create the search index definition 35 36 searchIndexModel := mongo.SearchIndexModel{ 37 Definition: bson.M{ 38 "mappings": bson.M{ 39 "dynamic": false, 40 "fields": bson.M{ 41 "plot": bson.M{ 42 "type": "string", 43 "analyzer": "lucene.english", 44 }, 45 }, 46 }, 47 "synonyms": []bson.M{ 48 { 49 "analyzer": "lucene.english", 50 "name": "my_synonyms", 51 "source": bson.M{ 52 "collection": "synonymous_terms", 53 }, 54 }, 55 }, 56 }, 57 Options: opts, 58 } 59 60 // Create the index 61 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel) 62 if err != nil { 63 log.Fatalf("Failed to create the Atlas Search index: %v", err) 64 } 65 66 fmt.Println("Name of index created: " + searchIndexName) 67 }
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
Set up your application.
To learn how to install the driver and configure your Go application, see the Get Started tutorial in the MongoDB Go Driver documentation.
Define the index.
Create a create-dynamic-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 16 // Replace the placeholder with your MongoDB deployment's connection string 17 uri := "<connection-string>" 18 client, err := mongo.Connect(options.Client(). 19 ApplyURI(uri)) 20 if err != nil { 21 panic(err) 22 } 23 24 defer func() { 25 if err := client.Disconnect(context.TODO()); err != nil { 26 panic(err) 27 } 28 }() 29 30 coll := client.Database("sample_mflix").Collection("movies") 31 const indexName = "default" 32 opts := options.SearchIndexes().SetName(indexName).SetType("search") 33 34 // Create the search index definition 35 searchIndexModel := mongo.SearchIndexModel{ 36 Definition: bson.M{ 37 "mappings": bson.M{ 38 "dynamic": true, 39 }, 40 "synonyms": []bson.M{ 41 { 42 "analyzer": "lucene.standard", 43 "name": "my_synonyms", 44 "source": bson.M{ 45 "collection": "synonymous_terms", 46 }, 47 }, 48 }, 49 }, 50 Options: opts, 51 } 52 53 // Create the index 54 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel) 55 if err != nil { 56 log.Fatalf("Failed to create the Atlas Search index: %v", err) 57 } 58 59 fmt.Println("Name of index created: " + searchIndexName) 60 }
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
Set up your application.
To learn how to install the driver and configure your Java application, see the Get Started tutorial in the MongoDB Java Driver documentation.
Define the index.
In your project's base package directory, create a CreateStaticIndex.java file and copy and paste the following code into this file.
1 import com.mongodb.client.*; 2 import org.bson.Document; 3 4 import java.util.List; 5 6 public class CreateStaticIndex { 7 public static void main(String[] args) { 8 // Replace the placeholder with your MongoDB deployment's connection string 9 String connectionString = "<connection-string>"; 10 11 try (MongoClient mongoClient = MongoClients.create(connectionString)) { 12 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 13 MongoCollection<Document> collection = database.getCollection("movies"); 14 String indexName = "default"; 15 16 // Define the synonym mapping for the lucene.english analyzer 17 List<Document> synonymsList = List.of( 18 new Document("analyzer", "lucene.english") 19 .append("name", "my_synonyms") 20 .append("source", new Document("collection", "synonymous_terms")) 21 ); 22 23 // Create the MongoDB Search index definition for the plot field with synonyms 24 Document searchIdx = new Document( 25 "mappings", 26 new Document("dynamic", false) 27 .append("fields", 28 new Document("plot", 29 new Document("type", "string") 30 .append("analyzer", "lucene.english") 31 ) 32 ) 33 ).append("synonyms", synonymsList); 34 35 // Create the index by using the Java Sync Driver 36 collection.createSearchIndex(indexName, searchIdx); 37 System.out.println("New index name: " + indexName); 38 } catch (Exception e) { 39 System.err.println("Error creating Atlas Search index: " + e.getMessage()); 40 } 41 } 42 }
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
Set up your application.
To learn how to install the driver and configure your Java application, see the Get Started tutorial in the MongoDB Java Driver documentation.
Define the index.
In your project's base package directory, create a CreateDynamicIndex.java file and copy and paste the following code into this file.
1 import com.mongodb.client.*; 2 import org.bson.Document; 3 4 import java.util.List; 5 6 public class CreateDynamicIndex { 7 public static void main(String[] args) { 8 // Replace the placeholder with your MongoDB deployment's connection string 9 String connectionString = "<connection-string>"; 10 11 try (MongoClient mongoClient = MongoClients.create(connectionString)) { 12 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 13 MongoCollection<Document> collection = database.getCollection("movies"); 14 String indexName = "default"; 15 16 // Define the synonym mapping for the lucene.standard analyzer 17 List<Document> synonymsList = List.of( 18 new Document("analyzer", "lucene.standard") 19 .append("name", "my_synonyms") 20 .append("source", new Document("collection", "synonymous_terms")) 21 ); 22 23 // Create the MongoDB Search index definition 24 Document searchIdx = new Document( 25 "mappings", 26 new Document("dynamic", true) 27 ).append("synonyms", synonymsList); 28 29 // Create the index by using the Java Sync Driver 30 collection.createSearchIndex(indexName, searchIdx); 31 System.out.println("New index name: " + indexName); 32 } catch (Exception e) { 33 System.err.println("Error creating Atlas Search index: " + e.getMessage()); 34 } 35 } 36 }
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
Set up your application.
To learn how to install the driver and configure your Node.js application, see the Get Started tutorial in the MongoDB Node.js Driver documentation.
Define the index.
Create a create-static-index.js file in your project directory, and copy and paste the following code into the file.
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the connection string with your MongoDB deployment's connection string 4 const uri = "<connection-string>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 const database = client.db("sample_mflix"); 11 const collection = database.collection("movies"); 12 13 // Create the MongoDB Search index definition for the plot field with synonyms 14 const index = { 15 name: "default", 16 definition: { 17 "mappings": { 18 "dynamic": false, 19 "fields": { 20 "plot": { 21 "type": "string", 22 "analyzer": "lucene.english" 23 } 24 } 25 }, 26 "synonyms": [ 27 { 28 "analyzer": "lucene.english", 29 "name": "my_synonyms", 30 "source": { 31 "collection": "synonymous_terms" 32 } 33 } 34 ] 35 } 36 } 37 38 // Create the index 39 const result = await collection.createSearchIndex(index); 40 console.log("New index name: " + result); 41 } finally { 42 await client.close(); 43 } 44 } 45 46 run().catch(console.dir);
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
Set up your application.
To learn how to install the driver and configure your Node.js application, see the Get Started tutorial in the MongoDB Node.js Driver documentation.
Define the index.
Create a create-dynamic-index.js file in your project directory, and copy and paste the following code into the file.
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the connection string with your MongoDB deployment's connection string 4 const uri = "<connection-string>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 const database = client.db("sample_mflix"); 11 const collection = database.collection("movies"); 12 13 // Create the MongoDB Search index definition with dynamic mapping and synonyms 14 const index = { 15 name: "default", 16 definition: { 17 "mappings": { 18 "dynamic": true 19 }, 20 "synonyms": [ 21 { 22 "analyzer": "lucene.standard", 23 "name": "my_synonyms", 24 "source": { 25 "collection": "synonymous_terms" 26 } 27 } 28 ] 29 } 30 } 31 32 // Create the index 33 const result = await collection.createSearchIndex(index); 34 console.log("New index name: " + result); 35 } finally { 36 await client.close(); 37 } 38 } 39 40 run().catch(console.dir);
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
Set up your application.
To learn how to install the driver and configure your Python application, see the Get Started tutorial in the MongoDB Python Driver documentation.
Define the index.
Create a create-static-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 database = client["sample_mflix"] 9 collection = database["movies"] 10 11 # Create the MongoDB Search index definition for the plot field with synonyms 12 search_index_model = SearchIndexModel( 13 definition={ 14 "mappings": { 15 "dynamic": False, 16 "fields": { 17 "plot": { 18 "type": "string", 19 "analyzer": "lucene.english" 20 } 21 } 22 }, 23 "synonyms": [ 24 { 25 "analyzer": "lucene.english", 26 "name": "my_synonyms", 27 "source": { 28 "collection": "synonymous_terms" 29 } 30 } 31 ] 32 }, 33 name="default", 34 ) 35 36 # Create the index 37 result = collection.create_search_index(model=search_index_model) 38 print(f"New index name: {result}")
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
Set up your application.
To learn how to install the driver and configure your Python application, see the Get Started tutorial in the MongoDB Python Driver documentation.
Define the index.
Create a create-dynamic-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 database = client["sample_mflix"] 9 collection = database["movies"] 10 11 # Create the MongoDB Search index definition 12 search_index_model = SearchIndexModel( 13 definition={ 14 "mappings": { 15 "dynamic": True, 16 }, 17 "synonyms": [ 18 { 19 "analyzer": "lucene.standard", 20 "name": "my_synonyms", 21 "source": { 22 "collection": "synonymous_terms" 23 } 24 } 25 ] 26 }, 27 name="default", 28 ) 29 30 # Create the index 31 result = collection.create_search_index(model=search_index_model) 32 print(f"New index name: {result}")
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
Create a static-index.json configuration file and specify the synonyms field.
1 { 2 "name": "default", 3 "collectionName": "movies", 4 "database": "sample_mflix", 5 "mappings": { 6 "dynamic": false, 7 "fields": { 8 "plot": { 9 "type": "string", 10 "analyzer": "lucene.english" 11 } 12 } 13 }, 14 "synonyms": [ 15 { 16 "analyzer": "lucene.english", 17 "name": "my_synonyms", 18 "source": { 19 "collection": "synonymous_terms" 20 } 21 } 22 ] 23 }
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 static-index.json file:
1 atlas deployments search indexes create --file <path-to-file>
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
Create a dynamic-index.json configuration file and specify the synonyms field.
1 { 2 "name": "default", 3 "collectionName": "movies", 4 "database": "sample_mflix", 5 "mappings": { 6 "dynamic": true 7 }, 8 "synonyms": [ 9 { 10 "analyzer": "lucene.standard", 11 "name": "my_synonyms", 12 "source": { 13 "collection": "synonymous_terms" 14 } 15 } 16 ] 17 }
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 dynamic-index.json file:
1 atlas deployments search indexes create --file <path-to-file>
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
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": false, 4 "fields": { 5 "plot": { 6 "type": "string", 7 "analyzer": "lucene.english" 8 } 9 } 10 }, 11 "synonyms": [ 12 { 13 "analyzer": "lucene.english", 14 "name": "my_synonyms", 15 "source": { 16 "collection": "synonymous_terms" 17 } 18 } 19 ] 20 } Click Create Search Index.
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
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 4 }, 5 "synonyms": [ 6 { 7 "analyzer": "lucene.standard", 8 "name": "my_synonyms", 9 "source": { 10 "collection": "synonymous_terms" 11 } 12 } 13 ] 14 } Click Create Search Index.
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
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.
Run the db.collection.createSearchIndex() method to create the index.
1 db.movies.createSearchIndex( 2 "default", 3 { 4 "mappings": { 5 "dynamic": false, 6 "fields": { 7 "plot": { 8 "type": "string", 9 "analyzer": "lucene.english" 10 } 11 } 12 }, 13 "synonyms": [ 14 { 15 "analyzer": "lucene.english", 16 "name": "my_synonyms", 17 "source": { 18 "collection": "synonymous_terms" 19 } 20 } 21 ]} 22 )
default
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
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.
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
Set up your application.
To learn how to install the driver and configure your C application, see the Get Started tutorial in the MongoDB C Driver documentation.
Define the index.
Create a create-static-index.c file in your application directory, and copy and paste the following code into the file.
1 2 3 4 int main(int argc, char *argv[]) { 5 mongoc_client_t *client; 6 mongoc_collection_t *collection; 7 bson_error_t error; 8 bson_t cmd; 9 bson_t *index_definition; 10 bool success; 11 12 /* Initialize the MongoDB C Driver. */ 13 mongoc_init(); 14 15 /* Connect to your MongoDB deployment. */ 16 client = mongoc_client_new("<connection-string>"); 17 collection = mongoc_client_get_collection (client, "sample_mflix", "movies"); 18 19 if (!client) { 20 fprintf(stderr, "Failed to create client.\n"); 21 return 1; 22 } 23 24 /* Create the MongoDB Search index definition for the plot field with synonyms. */ 25 char *cmd_str = bson_strdup_printf ( 26 BSON_STR ({ 27 "createSearchIndexes": "%s", 28 "indexes": [{ 29 "name": "default", 30 "definition": { 31 "mappings": { 32 "dynamic": false, 33 "fields": { 34 "plot": { 35 "type": "string", 36 "analyzer": "lucene.english" 37 } 38 } 39 }, 40 "synonyms": [ 41 { 42 "analyzer": "lucene.english", 43 "name": "my_synonyms", 44 "source": { 45 "collection": "synonymous_terms" 46 } 47 } 48 ] 49 } 50 }] 51 }), 52 "movies" 53 ); 54 bson_init_from_json (&cmd, cmd_str, -1, &error); 55 bson_free (cmd_str); 56 57 if (mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { 58 printf ("Index created!\n"); 59 } else { 60 fprintf (stderr, "Failed to create search index: %s", error.message); 61 } 62 63 /* Clean up. */ 64 bson_destroy (&cmd); 65 mongoc_collection_destroy (collection); 66 mongoc_client_destroy(client); 67 mongoc_cleanup(); 68 69 return 0; 70 }
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
Set up your application.
To learn how to install the driver and configure your C application, see the Get Started tutorial in the MongoDB C Driver documentation.
Define the index.
Create a create-dynamic-index.c file in your application directory, and copy and paste the following code into the file.
1 2 3 4 int main(int argc, char *argv[]) { 5 mongoc_client_t *client; 6 mongoc_collection_t *collection; 7 bson_error_t error; 8 bson_t cmd; 9 bson_t *index_definition; 10 bool success; 11 12 /* Initialize the MongoDB C Driver. */ 13 mongoc_init(); 14 15 /* Connect to your MongoDB deployment. */ 16 client = mongoc_client_new("<connection-string>"); 17 collection = mongoc_client_get_collection (client, "sample_mflix", "movies"); 18 19 if (!client) { 20 fprintf(stderr, "Failed to create client.\n"); 21 return 1; 22 } 23 24 /* Create the MongoDB Search index definition for a dynamic index with synonyms. */ 25 char *cmd_str = bson_strdup_printf ( 26 BSON_STR ({ 27 "createSearchIndexes": "%s", 28 "indexes": [{ 29 "name": "default", 30 "definition": { 31 "mappings": { 32 "dynamic": true 33 }, 34 "synonyms": [ 35 { 36 "analyzer": "lucene.standard", 37 "name": "my_synonyms", 38 "source": { 39 "collection": "synonymous_terms" 40 } 41 } 42 ] 43 } 44 }] 45 }), 46 "movies" 47 ); 48 bson_init_from_json (&cmd, cmd_str, -1, &error); 49 bson_free (cmd_str); 50 51 if (mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { 52 printf ("Index created!\n"); 53 } else { 54 fprintf (stderr, "Failed to create search index: %s", error.message); 55 } 56 57 /* Clean up. */ 58 bson_destroy (&cmd); 59 mongoc_collection_destroy (collection); 60 mongoc_client_destroy(client); 61 mongoc_cleanup(); 62 63 return 0; 64 }
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
Set up your application
To learn how to install the driver and configure your C++ application, see the Get Started tutorial in the MongoDB C++ Driver documentation.
Define the index.
Create a CreateStaticIndex.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 int main() { 13 // Initialize the MongoDB C++ driver 14 mongocxx::instance instance{}; 15 16 // Connect to your MongoDB deployment 17 mongocxx::uri uri("<connection-string>"); 18 mongocxx::client client(uri); 19 20 auto db = client["sample_mflix"]; 21 auto collection = db["movies"]; 22 auto siv = collection.search_indexes(); 23 24 // Create the MongoDB Search index definition for the plot field with synonyms 25 auto name = "default"; 26 auto synonyms = bsoncxx::builder::basic::make_array( 27 make_document( 28 kvp("analyzer", "lucene.english"), 29 kvp("name", "my_synonyms"), 30 kvp("source", make_document( 31 kvp("collection", "synonymous_terms") 32 )) 33 ) 34 ); 35 36 auto definition = make_document( 37 kvp("mappings", make_document( 38 kvp("dynamic", false), 39 kvp("fields", make_document( 40 kvp("plot", make_document( 41 kvp("type", "string"), 42 kvp("analyzer", "lucene.english") 43 )) 44 )) 45 )), 46 kvp("synonyms", synonyms) 47 ); 48 auto model = mongocxx::search_index_model(name, definition.view()); 49 50 try { 51 // Execute the command to create the index 52 auto result = siv.create_one(model); 53 std::cout << "New index name: " << result << std::endl; 54 } catch (const std::exception& e) { 55 std::cerr << "Error creating Atlas Search index: " << e.what() << std::endl; 56 } 57 58 }
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
Set up your application
To learn how to install the driver and configure your C++ application, see the Get Started tutorial in the MongoDB C++ Driver documentation.
Define the index.
Create a CreateDynamicIndex.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 int main() { 13 // Initialize the MongoDB C++ driver 14 mongocxx::instance instance{}; 15 16 // Connect to your MongoDB deployment 17 mongocxx::uri uri("<connection-string>"); 18 mongocxx::client client(uri); 19 20 auto db = client["sample_mflix"]; 21 auto collection = db["movies"]; 22 auto siv = collection.search_indexes(); 23 24 // Define the synonym mapping for the lucene.standard analyzer 25 auto name = "default"; 26 auto synonyms = bsoncxx::builder::basic::make_array( 27 make_document( 28 kvp("analyzer", "lucene.standard"), 29 kvp("name", "my_synonyms"), 30 kvp("source", make_document( 31 kvp("collection", "synonymous_terms") 32 )) 33 ) 34 ); 35 36 // Create the MongoDB Search index definition 37 auto definition = make_document( 38 kvp("mappings", make_document( 39 kvp("dynamic", true)) 40 ), 41 kvp("synonyms", synonyms) 42 ); 43 auto model = mongocxx::search_index_model(name, definition.view()); 44 45 try { 46 // Execute the command to create the index 47 auto result = siv.create_one(model); 48 std::cout << "New index name: " << result << std::endl; 49 } catch (const std::exception& e) { 50 std::cerr << "Error creating Atlas Search index: " << e.what() << std::endl; 51 } 52 53 }
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
Set up your application.
To learn how to install the driver and configure your Go application, see the Get Started tutorial in the MongoDB Go Driver documentation.
Define the index.
Create a create-static-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 16 // Replace the placeholder with your MongoDB deployment's connection string 17 uri := "<connection-string>" 18 client, err := mongo.Connect(options.Client(). 19 ApplyURI(uri)) 20 if err != nil { 21 panic(err) 22 } 23 24 defer func() { 25 if err := client.Disconnect(context.TODO()); err != nil { 26 panic(err) 27 } 28 }() 29 30 coll := client.Database("sample_mflix").Collection("movies") 31 const indexName = "default" 32 opts := options.SearchIndexes().SetName(indexName).SetType("search") 33 34 // Create the search index definition 35 36 searchIndexModel := mongo.SearchIndexModel{ 37 Definition: bson.M{ 38 "mappings": bson.M{ 39 "dynamic": false, 40 "fields": bson.M{ 41 "plot": bson.M{ 42 "type": "string", 43 "analyzer": "lucene.english", 44 }, 45 }, 46 }, 47 "synonyms": []bson.M{ 48 { 49 "analyzer": "lucene.english", 50 "name": "my_synonyms", 51 "source": bson.M{ 52 "collection": "synonymous_terms", 53 }, 54 }, 55 }, 56 }, 57 Options: opts, 58 } 59 60 // Create the index 61 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel) 62 if err != nil { 63 log.Fatalf("Failed to create the Atlas Search index: %v", err) 64 } 65 66 fmt.Println("Name of index created: " + searchIndexName) 67 }
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
Set up your application.
To learn how to install the driver and configure your Go application, see the Get Started tutorial in the MongoDB Go Driver documentation.
Define the index.
Create a create-dynamic-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 16 // Replace the placeholder with your MongoDB deployment's connection string 17 uri := "<connection-string>" 18 client, err := mongo.Connect(options.Client(). 19 ApplyURI(uri)) 20 if err != nil { 21 panic(err) 22 } 23 24 defer func() { 25 if err := client.Disconnect(context.TODO()); err != nil { 26 panic(err) 27 } 28 }() 29 30 coll := client.Database("sample_mflix").Collection("movies") 31 const indexName = "default" 32 opts := options.SearchIndexes().SetName(indexName).SetType("search") 33 34 // Create the search index definition 35 searchIndexModel := mongo.SearchIndexModel{ 36 Definition: bson.M{ 37 "mappings": bson.M{ 38 "dynamic": true, 39 }, 40 "synonyms": []bson.M{ 41 { 42 "analyzer": "lucene.standard", 43 "name": "my_synonyms", 44 "source": bson.M{ 45 "collection": "synonymous_terms", 46 }, 47 }, 48 }, 49 }, 50 Options: opts, 51 } 52 53 // Create the index 54 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel) 55 if err != nil { 56 log.Fatalf("Failed to create the Atlas Search index: %v", err) 57 } 58 59 fmt.Println("Name of index created: " + searchIndexName) 60 }
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
Set up your application.
To learn how to install the driver and configure your Java application, see the Get Started tutorial in the MongoDB Java Driver documentation.
Define the index.
In your project's base package directory, create a CreateStaticIndex.java file and copy and paste the following code into this file.
1 import com.mongodb.client.*; 2 import org.bson.Document; 3 4 import java.util.List; 5 6 public class CreateStaticIndex { 7 public static void main(String[] args) { 8 // Replace the placeholder with your MongoDB deployment's connection string 9 String connectionString = "<connection-string>"; 10 11 try (MongoClient mongoClient = MongoClients.create(connectionString)) { 12 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 13 MongoCollection<Document> collection = database.getCollection("movies"); 14 String indexName = "default"; 15 16 // Define the synonym mapping for the lucene.english analyzer 17 List<Document> synonymsList = List.of( 18 new Document("analyzer", "lucene.english") 19 .append("name", "my_synonyms") 20 .append("source", new Document("collection", "synonymous_terms")) 21 ); 22 23 // Create the MongoDB Search index definition for the plot field with synonyms 24 Document searchIdx = new Document( 25 "mappings", 26 new Document("dynamic", false) 27 .append("fields", 28 new Document("plot", 29 new Document("type", "string") 30 .append("analyzer", "lucene.english") 31 ) 32 ) 33 ).append("synonyms", synonymsList); 34 35 // Create the index by using the Java Sync Driver 36 collection.createSearchIndex(indexName, searchIdx); 37 System.out.println("New index name: " + indexName); 38 } catch (Exception e) { 39 System.err.println("Error creating Atlas Search index: " + e.getMessage()); 40 } 41 } 42 }
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
Set up your application.
To learn how to install the driver and configure your Java application, see the Get Started tutorial in the MongoDB Java Driver documentation.
Define the index.
In your project's base package directory, create a CreateDynamicIndex.java file and copy and paste the following code into this file.
1 import com.mongodb.client.*; 2 import org.bson.Document; 3 4 import java.util.List; 5 6 public class CreateDynamicIndex { 7 public static void main(String[] args) { 8 // Replace the placeholder with your MongoDB deployment's connection string 9 String connectionString = "<connection-string>"; 10 11 try (MongoClient mongoClient = MongoClients.create(connectionString)) { 12 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 13 MongoCollection<Document> collection = database.getCollection("movies"); 14 String indexName = "default"; 15 16 // Define the synonym mapping for the lucene.standard analyzer 17 List<Document> synonymsList = List.of( 18 new Document("analyzer", "lucene.standard") 19 .append("name", "my_synonyms") 20 .append("source", new Document("collection", "synonymous_terms")) 21 ); 22 23 // Create the MongoDB Search index definition 24 Document searchIdx = new Document( 25 "mappings", 26 new Document("dynamic", true) 27 ).append("synonyms", synonymsList); 28 29 // Create the index by using the Java Sync Driver 30 collection.createSearchIndex(indexName, searchIdx); 31 System.out.println("New index name: " + indexName); 32 } catch (Exception e) { 33 System.err.println("Error creating Atlas Search index: " + e.getMessage()); 34 } 35 } 36 }
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
Set up your application.
To learn how to install the driver and configure your Node.js application, see the Get Started tutorial in the MongoDB Node.js Driver documentation.
Define the index.
Create a create-static-index.js file in your project directory, and copy and paste the following code into the file.
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the connection string with your MongoDB deployment's connection string 4 const uri = "<connection-string>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 const database = client.db("sample_mflix"); 11 const collection = database.collection("movies"); 12 13 // Create the MongoDB Search index definition for the plot field with synonyms 14 const index = { 15 name: "default", 16 definition: { 17 "mappings": { 18 "dynamic": false, 19 "fields": { 20 "plot": { 21 "type": "string", 22 "analyzer": "lucene.english" 23 } 24 } 25 }, 26 "synonyms": [ 27 { 28 "analyzer": "lucene.english", 29 "name": "my_synonyms", 30 "source": { 31 "collection": "synonymous_terms" 32 } 33 } 34 ] 35 } 36 } 37 38 // Create the index 39 const result = await collection.createSearchIndex(index); 40 console.log("New index name: " + result); 41 } finally { 42 await client.close(); 43 } 44 } 45 46 run().catch(console.dir);
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
Set up your application.
To learn how to install the driver and configure your Node.js application, see the Get Started tutorial in the MongoDB Node.js Driver documentation.
Define the index.
Create a create-dynamic-index.js file in your project directory, and copy and paste the following code into the file.
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the connection string with your MongoDB deployment's connection string 4 const uri = "<connection-string>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 const database = client.db("sample_mflix"); 11 const collection = database.collection("movies"); 12 13 // Create the MongoDB Search index definition with dynamic mapping and synonyms 14 const index = { 15 name: "default", 16 definition: { 17 "mappings": { 18 "dynamic": true 19 }, 20 "synonyms": [ 21 { 22 "analyzer": "lucene.standard", 23 "name": "my_synonyms", 24 "source": { 25 "collection": "synonymous_terms" 26 } 27 } 28 ] 29 } 30 } 31 32 // Create the index 33 const result = await collection.createSearchIndex(index); 34 console.log("New index name: " + result); 35 } finally { 36 await client.close(); 37 } 38 } 39 40 run().catch(console.dir);
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.
The following examples for the sample_mflix.movies collection create index definitions that use static and dynamic mappings. These examples use the synonymous_terms synonym source collection described in the Synonym Source Collection Example section to enable synonym mappings.
Use Static Mappings
This example performs the following actions:
Configures an index with a single text field and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Analyzes the
plotfield with thelucene.englishanalyzer.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.englishanalyzer.
Set up your application.
To learn how to install the driver and configure your Python application, see the Get Started tutorial in the MongoDB Python Driver documentation.
Define the index.
Create a create-static-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 database = client["sample_mflix"] 9 collection = database["movies"] 10 11 # Create the MongoDB Search index definition for the plot field with synonyms 12 search_index_model = SearchIndexModel( 13 definition={ 14 "mappings": { 15 "dynamic": False, 16 "fields": { 17 "plot": { 18 "type": "string", 19 "analyzer": "lucene.english" 20 } 21 } 22 }, 23 "synonyms": [ 24 { 25 "analyzer": "lucene.english", 26 "name": "my_synonyms", 27 "source": { 28 "collection": "synonymous_terms" 29 } 30 } 31 ] 32 }, 33 name="default", 34 ) 35 36 # Create the index 37 result = collection.create_search_index(model=search_index_model) 38 print(f"New index name: {result}")
Use Dynamic Mappings
This example performs the following actions:
Configures an index for all document fields and a single synonym mapping definition that uses the mapping configured in the
synonymous_termscollection.Uses the default analyzer,
lucene.standard, to analyze all the fields.Enables synonyms from the
synonymous_termscollection for queries on fields analyzed with thelucene.standardanalyzer.
Set up your application.
To learn how to install the driver and configure your Python application, see the Get Started tutorial in the MongoDB Python Driver documentation.
Define the index.
Create a create-dynamic-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 database = client["sample_mflix"] 9 collection = database["movies"] 10 11 # Create the MongoDB Search index definition 12 search_index_model = SearchIndexModel( 13 definition={ 14 "mappings": { 15 "dynamic": True, 16 }, 17 "synonyms": [ 18 { 19 "analyzer": "lucene.standard", 20 "name": "my_synonyms", 21 "source": { 22 "collection": "synonymous_terms" 23 } 24 } 25 ] 26 }, 27 name="default", 28 ) 29 30 # Create the index 31 result = collection.create_search_index(model=search_index_model) 32 print(f"New index name: {result}")
Learn More
To learn how to add a collection that configures words as synonyms to your cluster, and use this collection to create a MongoDB Search index and run MongoDB Search queries using synonyms, see How to Use Synonyms with MongoDB Search.
To see examples of text queries that use synonyms, see Synonyms Examples in the text reference page.
To see an example phrase queries that uses synonyms, see Synonyms Example in the phrase reference page.