synonyms-tutorial

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

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

Available tabs: other tabs: transport, attire, single, multiple, equivalent, explicit, fts-vs, data-explorer, vib, jsonib, maven bom, gradle bom, maven, gradle -->

Learn to use synonyms with MongoDB Search to search for words that have the same or similar meaning. Select your deployment type, interface, and language below to view the appropriate tutorial.

This tutorial describes how to add a collection that configures words as synonyms, create an index that defines synonym mappings on the sample_mflix.movies collection, and run MongoDB Search queries against the title field using words that are configured as synonyms.

The tutorial takes you through the following steps:

  1. Load one or more sample synonyms source collections in the sample_mflix database.

  2. Create a MongoDB Search index with one or more synonym mappings for the sample_mflix.movies collection.

  3. Run MongoDB Search queries against the title field in the sample_mflix.movies collection for words configured as synonyms in the synonyms source collection.

Before you begin, ensure that your cluster meets the requirements described in the [Prerequisites.](https://www.mongodb.com/docs/search/query/accuracy.md#std-label-fts-accuracy-tutorials-prereqs

Note:

To create multiple synonym mappings and run the advanced sample query in this tutorial, you need an M10 or higher cluster.

Load the Sample Synonyms Source Collection with Compass

Each document in the synonyms source collection describe how one or more words map to one or more synonyms of those words. To learn more about the fields and word mapping types in the synonyms source collection documents, see [Format of Synonyms Source Collection Documents.](https://www.mongodb.com/docs/search/indexes/synonyms.md#std-label-synonyms-coll-format

To begin, you create the synonyms source collection and then add the collection to the database where you intend to use the synonyms source collection. In this section, you create one or two sample synonyms source collections in the sample_mflix database using the MongoDB C++ driver, and then use the synonyms source collections with an index of the movies collection in the same database.

If you are running a Free cluster or a Flex cluster, follow the steps in the Transportation Synonyms tab to create the collection for a single synonym mapping definition in your index. If you have a M10 or higher cluster and wish to create multiple synonym mappings in your index, follow the steps in both the tabs to create both the Transportation Synonyms and Attire Synonyms collections.

Transport Synonyms

Create and populate the transport_synonyms collection:

  1. Connect to your cluster using MongoDB Compass.

Open Compass and connect to your cluster. For detailed instructions, see [Connect to a Cluster via Compass.](https://www.mongodb.com/docs/atlas/compass-connection.md#std-label-atlas-connect-via-compass

  1. Create the collection.

On the Database screen, select the database sample_mflix, then select Create Collection.

  1. Specify the collection name.

Enter transport_synonyms as the collection name and select Create Collection.

  1. Load sample data into the collection.

Select the transport_synonyms collection if it's not already selected.

Click Add Data for each of the sample documents to add to the collection.

Click Insert Document to replace the default document.

Copy and paste the following sample documents, one at a time, and click Insert to add the documents, one at a time, to the collection.

json { "mappingType": "equivalent", "synonyms": ["car", "vehicle", "automobile"] }

json { "mappingType": "explicit", "input": ["boat"], "synonyms": ["boat", "vessel", "sail"] }

Create the MongoDB Search Index

  1. Connect to your cluster using MongoDB Compass.

Open Compass and connect to your cluster. For detailed instructions, see [Connect to a Cluster via Compass.](https://www.mongodb.com/docs/atlas/compass-connection.md#std-label-atlas-connect-via-compass

  1. Specify the database and collection.

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

  1. Define the index.

To run the simple example query only, use the index definition in the Single Synonym Mapping tab below. If you have an M10 or higher cluster and if you loaded both the example synonyms source collections, you can run both the simple and advanced example queries using the index definition that specifies multiple synonym mappings in the Multiple Synonym Mappings tab below.

### Single Synonym Mapping

Click the Indexes tab, then select Search Indexes.

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

Name the index, default.

Specify the JSON (Javascript Object Notation) MongoDB Search index definition.

The following index definition specifies:

  • The [language analyzer](https://www.mongodb.com/docs/search/indexes/analyzers/language.md#std-label-ref-language-analyzers lucene.english as the default analyzer for both indexing and querying the title field.

  • The name transportSynonyms as the name for this synonym mapping.

  • The transport_synonyms collection as the source synonyms collection to look for synonyms for queries using transportSynonyms mapping. transportSynonyms can be used in text queries over any field indexed with the lucene.english analyzer (including the title field, in this example).

json { "mappings": { "dynamic": false, "fields": { "title": { "analyzer": "lucene.english", "type": "string" } } }, "synonyms": [ { "analyzer": "lucene.english", "name": "transportSynonyms", "source": { "collection": "transport_synonyms" } } ] }

Click Create Search Index.

Search the Collection

Synonyms can be used only in queries that use the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator. In this section, you connect to your cluster and then run the sample queries using the text operator against the title field in the sample_mflix.movies collection. The sample queries use words that are configured as synonyms of different mapping types in the synonyms source collection. The source collection is referenced in the synonyms mapping that the queries use.

  1. Connect to your cluster in MongoDB Compass.

Open MongoDB Compass and connect to your cluster. For detailed instructions on connecting, see [Connect to a Cluster via Compass.](https://www.mongodb.com/docs/atlas/compass-connection.md#std-label-atlas-connect-via-compass

  1. Use the movies collection in the sample_mflix database.

On the Database screen, click the sample_mflix database, then click the movies collection.

  1. Run simple MongoDB Search queries on the movies collection. MongoDB Search query results vary based on the type of word mapping defined in the synonyms source collection.

### equivalent Mapping Type

The query searches the title field for the word automobile and uses the synonym mapping definition named transportSynonyms to search for words configured as synonyms of the query word automobile in the synonyms source collection named transport_synonyms. The query includes the following stages:

  • [$limit](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit stage to limit the output to 10 results

  • [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to exclude all fields except title and add a field named score

To run this query in MongoDB Compass:

Click the Aggregations tab.

Click Select..., then configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click Add Stage to add additional stages.

Pipeline Stage Query
$search `{
“index”: “synonyms-tutorial”,
“text”: {
“path”: “title”,
“query”: “automobile”,
“synonyms”: “transportSynonyms”
}
}`
$limit 10
$project `{
“_id”: 0,
“title”: 1,
“score”: { “$meta”: “searchScore” }
}`

If you [enabled](https://www.mongodb.com/docs/compass/current/aggregation-pipeline-builder/#set-the-documents-limit-or-auto-preview-documents Auto Preview, MongoDB Compass displays the following documents next to the $project pipeline stage:

json {title Cars} {score 4.197734832763672} {title Planes, Trains & Automobiles} {score 3.8511905670166016} {title Car Wash} {score 3.39473032951355} {title Used Cars} {score 3.39473032951355} {title Blue Car} {score 3.39473032951355} {title Cars 2} {score 3.39473032951355} {title Stealing Cars} {score 3.39473032951355} {title Cop Car} {score 3.39473032951355} {title The Cars That Eat People} {score 2.8496146202087402} {title Khrustalyov, My Car!} {score 2.8496146202087402}

The MongoDB Search results contain movies with car and automobile in the title field although the query term is automobile because we configured automobile to be a synonym of car, vehicle, and automobile in the synonyms source collection named sample_synonyms, which is specified in the index for the collection. MongoDB Search returns the same results for a search of the words car and vehicle. To test this, replace the value of the query field in the query above with either car or vehicle and run the query.

  1. Run advanced MongoDB Search queries if you created the index that contains multiple synonym mappings. MongoDB Search query results vary based on the type of word mapping defined in the synonyms source collection.

### equivalent Mapping Type

The query searches the title field for the word automobile and uses the synonym mapping definition named transportSynonyms to search for words configured as synonyms of the query word automobile in the synonyms source collection named transport_synonyms. The query searches the title field for the word attire also and uses the synonym mapping definition named attireSynonyms to search for words configured as synonyms of the query word attire in the synonyms source collection named attire_synonyms.

The query includes the following stages:

  • [$limit](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit stage to limit the output to 10 results

  • [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to exclude all fields except title and add a field named score

To run this query in MongoDB Compass:

Click the Aggregations tab.

Click Select..., then configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click Add Stage to add additional stages.

Pipeline Stage Query
$search `{
“index”: “synonyms-tutorial”,
“compound”: {
“should”: [{
“text”: {
“path”: “title”,
“query”: “automobile”,
“synonyms”: “transportSynonyms”
}
},
{
“text”: {
“path”: “title”,
“query”: “attire”,
“synonyms”: “attireSynonyms”
}
}]
}
}`
$limit 10
$project `{
“_id”: 0,
“title”: 1,
“score”: { “$meta”: “searchScore” }
}`

If you [enabled](https://www.mongodb.com/docs/compass/current/aggregation-pipeline-builder/#set-the-documents-limit-or-auto-preview-documents Auto Preview, MongoDB Compass displays the following documents next to the $project pipeline stage:

json { title: 'The Dress', score: 4.812004089355469 }, { title: 'Cars', score: 4.197734832763672 }, { title: 'Dressed to Kill', score: 3.891493320465088 }, { title: '27 Dresses', score: 3.891493320465088 }, { title: 'Planes, Trains & Automobiles', score: 3.8511905670166016 }, { title: 'Car Wash', score: 3.39473032951355 }, { title: 'Used Cars', score: 3.39473032951355 }, { title: 'Blue Car', score: 3.39473032951355 }, { title: 'Cars 2', score: 3.39473032951355 }, { title: 'Stealing Cars', score: 3.39473032951355 }

The MongoDB Search results contain documents for both the search terms. The results contain movies with car in the title field for the query term automobile because we configured automobile to be a synonym of car, vehicle, and automobile in the synonyms source collection named transport_synonyms. The result also contains movies with dress in the title field for the query term attire because we configured attire to be a synonym of dress, apparel, and attire in the synonyms source collection named attire_synonyms.

MongoDB Search returns the same results for a search of car or vehicle in the transport_synonyms source collection and dress or apparel in the attire_synonyms source collection. To test this example, replace the value of the query field in the query above with car or vehicle and replace the value of the query field in the query above with dress or apparel, and run the query again.

This tutorial describes how to add a collection that configures words as synonyms, create an index that defines synonym mappings on the sample_mflix.movies collection, and run MongoDB Search queries against the title field using words that are configured as synonyms.

The tutorial takes you through the following steps:

  1. Load one or more sample synonyms source collections in the sample_mflix database.

  2. Create a MongoDB Search index with one or more synonym mappings for the sample_mflix.movies collection.

  3. Run MongoDB Search queries against the title field in the sample_mflix.movies collection for words configured as synonyms in the synonyms source collection.

Before you begin, ensure that your cluster meets the requirements described in the [Prerequisites.](https://www.mongodb.com/docs/search/query/accuracy.md#std-label-fts-accuracy-tutorials-prereqs

Note:

To create multiple synonym mappings and run the advanced sample query in this tutorial, you need an M10 or higher cluster.

Load the Sample Synonyms Source Collection using the Mongo Shell

Each document in the synonyms source collection describe how one or more words map to one or more synonyms of those words. To learn more about the fields and word mapping types in the synonyms source collection documents, see [Format of Synonyms Source Collection Documents.](https://www.mongodb.com/docs/search/indexes/synonyms.md#std-label-synonyms-coll-format

To begin, you create the synonyms source collection and then add the collection to the database where you intend to use the synonyms source collection. In this section, you create one or two sample synonyms source collections in the sample_mflix database, and then use the synonyms source collections with an index of the movies collection in the same database.

If you are running a Free cluster or a Flex cluster, follow the steps in the Transportation Synonyms tab to create the collection for a single synonym mapping definition in your index. If you have a M10 or higher cluster and wish to create multiple synonym mappings in your index, follow the steps in both the tabs to create both the Transportation Synonyms and Attire Synonyms collections.

Transport Synonyms

Create and populate the transport_synonyms collection:

  1. Connect to the deployment using mongosh.

In your terminal, connect to your Atlas cloud-hosted deployment or local deployment from [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh. For detailed instructions on how to connect, see Connect to a Deployment.

  1. Switch to the sample_mflix database.

shell use sample_mflix

Output:

shell switched to db sample_mflix

  1. Create the transport_synonyms collection.

shell db.createCollection("transport_synonyms")

Output:

shell { "ok" : 1 }

  1. Insert documents into the transport_synonyms collection.

Insert the following documents that define synonym mappings:

shell db.transport_synonyms.insertMany([ { "mappingType": "equivalent", "synonyms": ["car", "vehicle", "automobile"] }, { "mappingType": "explicit", "input": ["boat"], "synonyms": ["boat", "vessel", "sail"] } ])

Output:

shell { "acknowledged" : true, "insertedIds" : [ ObjectId("..."), ObjectId("...") ] }

Create the MongoDB Search Index

  1. Connect to the deployment by using mongosh.

In your terminal, connect to your Atlas cloud-hosted deployment or local deployment from [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh. For detailed instructions on how to connect, see Connect to a Deployment.

  1. Switch to the database that contains the collection for which you want to create the index.

shell use sample_mflix

Output:

shell switched to db sample_mflix

  1. Run the db.collection.createSearchIndex() method to create the index.

To run the simple example query only, run the command in the Single Synonym Mapping tab below. If you have an M10 or higher cluster and if you loaded both the example synonyms source collections, you can run both the simple and advanced example queries using the command that specifies multiple synonym mappings in the Multiple Synonym Mappings tab below.

### Single Synonym Mapping

The following index definition specifies:

  • The [language analyzer](https://www.mongodb.com/docs/search/indexes/analyzers/language.md#std-label-ref-language-analyzers lucene.english as the default analyzer for both indexing and querying the title field.

  • The name transportSynonyms as the name for this synonym mapping.

  • The transport_synonyms collection as the source synonyms collection to look for synonyms for queries using transportSynonyms mapping. transportSynonyms can be used in text queries over any field indexed with the lucene.english analyzer (including the title field, in this example).

shell db.movies.createSearchIndex( "default", { "mappings": { "dynamic": false, "fields": { "title": { "analyzer": "lucene.english", "type": "string" } } }, "synonyms": [ { "analyzer": "lucene.english", "name": "transportSynonyms", "source": { "collection": "transport_synonyms" } } ] } )

Output:

text default

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

##### Atlas Cluster Connection String

Your connection string should use the following format:

text mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

To learn more, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver

##### Local or Self-Managed Connection String

Your connection string should use the following format:

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

To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri

Search the Collection

Synonyms can be used only in queries that use the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator. In this section, you connect to your cluster and then run the sample queries using the text operator against the title field in the sample_mflix.movies collection. The sample queries use words that are configured as synonyms of different mapping types in the synonyms source collection. The source collection is referenced in the synonyms mapping that the queries use.

  1. Connect to your cluster in [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh.

Open [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh in a terminal window and connect to your cluster. For detailed instructions on connecting, see [Connect to a Cluster via mongosh.](https://www.mongodb.com/docs/atlas/mongo-shell-connection.md#std-label-connect-mongo-shell

  1. Use the sample_mflix database.

Run the following command at [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh prompt:

javascript use sample_mflix

  1. Run the following example queries on the movies collection. If you created an index with a single synonym mapping definition, run the query in the Simple Example section below. If you defined multiple synonym mappings in your index, you can run the queries in both the sections below.

These queries use the following pipeline stages:

  • [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search stage to search the collection.

  • [$limit](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit stage to limit the output to 10 results.

  • [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to:

    • Exclude all fields except the title field.

    • Add a field named score.

#### Simple Example

MongoDB Search query results vary based on the type of word mapping defined in the synonyms source collection.

### equivalent Mapping Type

The query searches the title field for the word automobile and uses the synonym mapping definition named transportSynonyms to search for words configured as synonyms of the query word automobile in the synonyms source collection named transport_synonyms.

json db.movies.aggregate([ { $search: { "index": "synonyms-tutorial", "text": { "path": "title", "query": "automobile", "synonyms": "transportSynonyms" } } }, { $limit: 10 }, { $project: { "_id": 0, "title": 1, "score": { $meta: "searchScore" } } } ])

Output:

json { "title" : "Cars", "score" : 4.197734832763672 } { "title" : "Planes, Trains & Automobiles", "score" : 3.8511905670166016 } { "title" : "Car Wash", "score" : 3.39473032951355 } { "title" : "Used Cars", "score" : 3.39473032951355 } { "title" : "Blue Car", "score" : 3.39473032951355 } { "title" : "Cars 2", "score" : 3.39473032951355 } { "title" : "Stealing Cars", "score" : 3.39473032951355 } { "title" : "Cop Car", "score" : 3.39473032951355 } { "title" : "The Cars That Eat People", "score" : 2.8496146202087402 } { "title" : "Khrustalyov, My Car!", "score" : 2.8496146202087402 }

The MongoDB Search results contain movies with car and automobile in the title field although the query term is automobile because we configured automobile to be a synonym of car, vehicle, and automobile in the synonyms source collection named sample_synonyms, which is specified in the index for the collection. MongoDB Search returns the same results for a search of the words car and vehicle. To test this, replace the value of the query field in the query above with either car or vehicle and run the query.

#### Advanced Example

MongoDB Search query results vary based on the type of word mapping defined in the synonyms source collection.

### equivalent Mapping Type

The query searches the title field for the word automobile and uses the synonym mapping definition named transportSynonyms to search for words configured as synonyms of the query word automobile in the synonyms source collection named transport_synonyms. The query searches the title field for the word attire also and uses the synonym mapping definition named attireSynonyms to search for words configured as synonyms of the query word attire in the synonyms source collection named attire_synonyms.

json db.movies.aggregate([ { $search: { "index": "synonyms-tutorial", "compound": { "should": [{ "text": { "path": "title", "query": "automobile", "synonyms": "transportSynonyms" } }, { "text": { "path": "title", "query": "attire", "synonyms": "attireSynonyms" } }] } } }, { $limit: 10 }, { $project: { "_id": 0, "title": 1, "score": { $meta: "searchScore" } } } ])

Output:

json [ { title: 'The Dress', score: 4.812004089355469 }, { title: 'Cars', score: 4.197734832763672 }, { title: 'Dressed to Kill', score: 3.891493320465088 }, { title: '27 Dresses', score: 3.891493320465088 }, { title: 'Planes, Trains & Automobiles', score: 3.8511905670166016 }, { title: 'Car Wash', score: 3.39473032951355 }, { title: 'Used Cars', score: 3.39473032951355 }, { title: 'Blue Car', score: 3.39473032951355 }, { title: 'Cars 2', score: 3.39473032951355 }, { title: 'Stealing Cars', score: 3.39473032951355 } ]

The MongoDB Search results contain documents for both the search terms. The results contain movies with car in the title field for the query term automobile because we configured automobile to be a synonym of car, vehicle, and automobile in the synonyms source collection named transport_synonyms. The result also contains movies with dress in the title field for the query term attire because we configured attire to be a synonym of dress, apparel, and attire in the synonyms source collection named attire_synonyms.

MongoDB Search returns the same results for a search of car or vehicle in the transport_synonyms source collection and dress or apparel in the attire_synonyms source collection. To test this example, replace the value of the query field in the query above with car or vehicle and replace the value of the query field in the query above with dress or apparel, and run the query again.

This tutorial describes how to add a collection that configures words as synonyms, create an index that defines synonym mappings on the sample_mflix.movies collection, and run MongoDB Search queries against the title field using words that are configured as synonyms.

The tutorial takes you through the following steps:

  1. Load one or more sample synonyms source collections in the sample_mflix database.

  2. Create a MongoDB Search index with one or more synonym mappings for the sample_mflix.movies collection.

  3. Run MongoDB Search queries against the title field in the sample_mflix.movies collection for words configured as synonyms in the synonyms source collection.

Before you begin, ensure that your cluster meets the requirements described in the [Prerequisites.](https://www.mongodb.com/docs/search/query/accuracy.md#std-label-fts-accuracy-tutorials-prereqs

Note:

To create multiple synonym mappings and run the advanced sample query in this tutorial, you need an M10 or higher cluster.

Load the Sample Synonyms Source Collection in the Atlas UI

Each document in the synonyms source collection describe how one or more words map to one or more synonyms of those words. To learn more about the fields and word mapping types in the synonyms source collection documents, see [Format of Synonyms Source Collection Documents.](https://www.mongodb.com/docs/search/indexes/synonyms.md#std-label-synonyms-coll-format

To begin, you create the synonyms source collection and then add the collection to the database where you intend to use the synonyms source collection. In this section, you create one or two sample synonyms source collections in the sample_mflix database, and then use the synonyms source collections with an index of the movies collection in the same database.

  1. In Atlas, go to the Clusters page for your project.

If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.

If it's not already displayed, select your desired project from the Projects menu in the navigation bar.

In the sidebar, click Clusters under the Database heading.

The Clusters page displays.

  1. In Atlas, go to the Data Explorer page for your project.

If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.

If it's not already displayed, select your project from the Projects menu in the navigation bar.

In the sidebar, click Data Explorer under the Database heading.

The Data Explorer displays.

  1. Create one or more sample synonyms collections in the sample_mflix database.

If you are running a Free cluster or a Flex cluster, follow the steps in the Transportation Synonyms tab to create the collection for a single synonym mapping definition in your index. If you have a M10 or higher cluster and wish to create multiple synonym mappings in your index, follow the steps in both the tabs to create both the Transportation Synonyms and Attire Synonyms collections.

### Transport Synonyms

Expand the sample_mflix database and click the icon to open the Create Collection modal.

Type transport_synonyms in the Collection name field.

Click Create to create the collection in the sample_mflix database.

  1. Load the sample data into the synonyms collection.

Follow the steps in the tabs to load data into the respective collection.

### Transport Synonyms

Select the transport_synonyms collection if it's not selected.

Click Insert Document for each of the sample documents to add to the collection.

Click the JSON (Javascript Object Notation) view ({}) to replace the default document.

Copy and paste the following sample documents, one at a time, and click Insert to add the documents, one at a time, to the collection.

json { "mappingType": "equivalent", "synonyms": ["car", "vehicle", "automobile"] }

json { "mappingType": "explicit", "input": ["boat"], "synonyms": ["boat", "vessel", "sail"] }

Create the MongoDB Search Index

The synonym mapping in a collection's [index](https://www.mongodb.com/docs/search/indexes/synonyms.md#std-label-synonyms-ref specifies the synonyms source collection and the analyzer to use with the collection.

In this section, you create a MongoDB Search index that defines one or many synonym mappings for the sample_mflix.movies collection. The mapping definition in the index references the synonyms source collection that you created in the sample_mflix database.

  1. In Atlas, go to the Search & Vector Search page for your cluster.

You can go the MongoDB Search page from the Search & Vector Search option, or the Data Explorer.

### Search & Vector Search

If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.

If it's not already displayed, select your project from the Projects menu in the navigation bar.

In the sidebar, click Search & Vector Search under the Database heading.

  • If you have no clusters, click Create cluster to create one. To learn more, see [Create an Atlas Infinite or Atlas Core Cluster.](https://www.mongodb.com/docs/atlas/tutorial/create-new-cluster.md#std-label-create-new-cluster

  • If your project has multiple clusters, select the cluster you want to use from the Select cluster dropdown, then click Go to Search.

The Search & Vector Search page displays.

  1. Click Create Search Index.

  2. Start your index configuration.

Make the following selections on the page and then click Next.

Search Type Select the Atlas Search index type.
Index Name and Data Source Specify the following information: Index Name: synonyms-tutorial; Database and Collection:sample_mflix database; movies collection
Configuration Method For a guided experience, select Visual Editor.To edit the raw index definition, select JSON Editor.

IMPORTANT: The default index name varies by index type: your MongoDB Search index is named default, your Vector Search index is named vector_index, and your Automated Embedding index is named autoembed_index. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.

  1. Modify the default index definition.

To run the simple example query only, use the index definition in the Single Synonym Mapping section below. If you have an M10 or higher cluster and if you loaded both the example synonyms source collections, you can run both the simple and advanced example queries using the index definition that specifies multiple synonym mappings in the Multiple Synonym Mappings section below.

##### Single Synonym Mapping

The following index definition specifies:

  • The [language analyzer](https://www.mongodb.com/docs/search/indexes/analyzers/language.md#std-label-ref-language-analyzers lucene.english as the default analyzer for both indexing and querying the title field.

  • The name transportSynonyms as the name for this synonym mapping.

  • The transport_synonyms collection as the source synonyms collection to look for synonyms for queries using transportSynonyms mapping. transportSynonyms can be used in text queries over any field indexed with the lucene.english analyzer (including the title field, in this example).

### Visual Editor

Click Refine Your Index.

Click Add Field in the Field Mappings section.

Click Customized Configuration.

Configure the following fields in the Add Field Mapping window and click Add after:

UI Field Name Configuration
Field Name Enter title.
Enable Dynamic Mapping Toggle to Off.
Data Type Configuration Click Add Data Type.Select String.For Index Analyzer and Search Analyzer, click the dropdown to select lucene.english from the lucene.language analyzers dropdown.

For all other fields not listed above, accept the default.

Click Add Synonym Mapping in the Synonym Mappings section.

Configure the following fields in the Add Synonym Mapping window and click Add after:

UI Field Name Configuration
Synonym Mapping Name Enter transportSynonyms.
Synonym Source Collection Select transport_synonyms.
Analyzer Select lucene.english.

Click Save Changes.

##### Multiple Synonym Mappings

The following index definition specifies:

  • The lucene.english [language analyzer](https://www.mongodb.com/docs/search/indexes/analyzers/language.md#std-label-ref-language-analyzers as the default analyzer for both indexing and querying the title field.

  • The name transportSynonyms and attireSynonyms as the names for the synonym mappings.

    • The transport_synonyms collection as the source synonyms collection to look for synonyms for queries using transportSynonyms mapping. transportSynonyms can be used in text queries over any field indexed with the lucene.english analyzer (including the title field, in the sample query in this tutorial).

    • The attire_synonyms collection as the source synonyms collection to look for synonyms for queries using attireSynonyms mapping. attireSynonyms can be used in text queries over any field indexed with the lucene.english analyzer (including the title field, in the sample query in this tutorial).

### Visual Editor

Click Refine Your Index.

Click Add Field in the Field Mappings section.

Configure the following fields in the Add Field Mapping window and then click Add:

UI Field Name Configuration
Field Name Enter title.
Enable Dynamic Mapping Toggle to Off.
Data Type Configuration Select String.For Index Analyzer and Search Analyzer, click the dropdown to select lucene.english from the lucene.language analyzers dropdown.

For all other fields not listed above, accept the default.

Click Add Synonym Mapping in the Synonym Mappings section.

Configure the following fields in the Add Synonym Mapping window and then click Add:

UI Field Name Configuration
Synonym Mapping Name Enter transportSynonyms.
Synonym Source Collection Select transport_synonyms.
Analyzer Select lucene.english.

Click Add Synonym Mapping again in the Synonym Mappings section.

Configure the following fields in the Add Synonym Mapping window and click Add after:

UI Field Name Configuration
Synonym Mapping Name Enter attireSynonyms.
Synonym Source Collection Select attire_synonyms.
Analyzer Select lucene.english.

Click Save Changes.

  1. Click Create Search Index.

  2. Close the You're All Set! Modal Window.

A modal window appears to let you know your index is building. Click the Close button.

  1. Wait for the index to finish building.

The index should take about one minute to build. While it is building, the Status column reads Build in Progress. When it is finished building, the Status column reads Active.

Search the Collection

Synonyms can be used only in queries that use the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator. In this section, you connect to your cluster and then run the sample queries using the text operator against the title field in the sample_mflix.movies collection. The sample queries use words that are configured as synonyms of different mapping types in the synonyms source collection. The source collection is referenced in the synonyms mapping that the queries use.

  1. In Atlas, go to the Search & Vector Search page for your cluster.

You can go the MongoDB Search page from the Search & Vector Search option, or the Data Explorer.

### Search & Vector Search

If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.

If it's not already displayed, select your project from the Projects menu in the navigation bar.

In the sidebar, click Search & Vector Search under the Database heading.

  • If you have no clusters, click Create cluster to create one. To learn more, see [Create an Atlas Infinite or Atlas Core Cluster.](https://www.mongodb.com/docs/atlas/tutorial/create-new-cluster.md#std-label-create-new-cluster

  • If your project has multiple clusters, select the cluster you want to use from the Select cluster dropdown, then click Go to Search.

The Search & Vector Search page displays.

  1. Go to the Search Tester.

Click the Query button to the right of the index to query.

  1. View and edit the query syntax.

Click Edit Query to view a default query syntax sample in JSON (Javascript Object Notation) format.

  1. Run the following example queries on the movies collection.

If you created an index with a single synonym mapping definition, run the query from the following Simple Example section. If you defined multiple synonym mappings in your index, you can run the queries from both of the following sections.

The following queries:

  • Exclude all fields except the title field.

  • Add a field named score.

#### Simple Example

MongoDB Search query results vary based on the type of word mapping defined in the synonyms source collection.

### equivalent Mapping Type

The following query searches the title field for automobile and uses the transportSynonyms synonym mapping definition to search for the synonyms of automobile that you configured in the transport_synonyms synonyms source collection.

json [ { $search: { index: "synonyms-tutorial", text: { path: "title", query: "automobile", synonyms: "transportSynonyms" } } } ]

Output:

```text SCORE: 4.197734832763672 _id: “573a13a9f29313caabd1f18a” fullplot: "While traveling to California for the dispute of the final race of the…" imdb: Object year: 2006 ... title: "Cars"

SCORE: 3.8511905670166016 _id: “573a1398f29313caabcea94c” plot: "A man must struggle to travel home for Thanksgiving with an obnoxious …" genres: Array runtime: 93 ... title: "Planes, Trains, and Automobiles"

SCORE: 3.39473032951355 _id: “573a1397f29313caabce5fb0” plot: "Car Wash is about a close-knit group of employees who one day have all…" genres: Array runtime: 97 ... title: "Car Wash"

SCORE: 3.39473032951355 _id: “573a1397f29313caabce7bd2” plot: "When the owner of a struggling used car lot is killed, it's up to the …" genres: Array runtime: 113 ... title: "Used Cars"

SCORE: 3.39473032951355 _id: “573a13a6f29313caabd18bfe” fullplot: "Gifted 18-year-old Meg has been abandoned by her father and neglected …" imdb: Object year: 2002 ... title: "Blue Car"

SCORE: 3.39473032951355 _id: “573a13c1f29313caabd64e3d” fullplot: "After Mater gets his best friend, star race car Lightning McQueen, a s…" imdb: Object year: 2011 ... title: "Cars 2"

SCORE: 3.39473032951355 _id: “573a13eaf29313caabdce62c” plot: "A rebellious teenager navigates his way through the juvenile court sys…" genres: Array runtime: 94 ... title: "Stealing Cars"

SCORE: 3.39473032951355 _id: “573a13f1f29313caabddc93f” plot: "A small town sheriff sets out to find the two kids who have taken his …" genres: Array runtime: 86 ... title: "Cop Car"

SCORE: 2.8496146202087402 _id: “573a1396f29313caabce5480” plot: "The small town of Paris, Australia deliberately causes car accidents, …" genres: Array runtime: 91 ... title: "The Cars That Eat People"

SCORE: 2.8496146202087402 _id: “573a139df29313caabcf9636” plot: "Military doctor General Klenski is arrested in Stalin's Russia in 1953…" genres: Array runtime: 137 ... title: "Khrustalyov, My Car!" ```

The MongoDB Search results contain movies with car and automobile in the title field although the query term is automobile because we configured automobile to be a synonym of car, vehicle, and automobile in the synonyms s

(本文超出站点单文档体积上限,已截断)