Docs Menu
Docs Home
/
MongoDB Atlas
/ /

How to Use Synonyms with Atlas Search

On this page

  • Load the Sample Synonyms Source Collection
  • Create the Atlas Search Index With Synonym Mapping Definition
  • Search the Collection

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 Atlas 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 an Atlas Search index with one or more synonym mappings for the sample_mflix.movies collection.

  3. Run Atlas 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 Atlas cluster meets the requirements described in the Prerequisites.

Note

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

To create an Atlas Search index, you must have Project Data Access Admin or higher access to the project.

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.

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
  1. If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.

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

  3. If it's not already displayed, click Clusters in the sidebar.

    The Clusters page displays.

2

Click the Browse Collections button for your cluster.

The Data Explorer displays.

3

If you are running a free or shared tier 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.

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

  2. Type transport_synonyms in the Collection name field.

  3. Click Create to create the collection in the sample_mflix database.

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

  2. Type attire_synonyms in the Collection name field.

  3. Click Create to create the collection in the sample_mflix database.

4

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

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

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

  3. Click the JSON view ({}) to replace the default document.

  4. 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.

    {
    "mappingType": "equivalent",
    "synonyms": ["car", "vehicle", "automobile"]
    }
    {
    "mappingType": "explicit",
    "input": ["boat"],
    "synonyms": ["boat", "vessel", "sail"]
    }
  1. Select the attire_synonyms collection if it's not selected.

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

  3. Click the JSON view ({}) to replace the default document.

  4. 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.

    {
    "mappingType": "equivalent",
    "synonyms": ["dress", "apparel", "attire"]
    }
    {
    "mappingType": "explicit",
    "input": ["hat"],
    "synonyms": ["hat", "fedora", "headgear"]
    }

The synonym mapping in a collection's index specifies the synonyms source collection and the analyzer to use with the collection.

In this section, you create an Atlas 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
  1. If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.

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

  3. If it's not already displayed, click Clusters in the sidebar.

    The Clusters page displays.

2

You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.

  1. In the sidebar, click Atlas Search under the Services heading.

  2. From the Select data source dropdown, select your cluster and click Go to Atlas Search.

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3
4
  • For a guided experience, select the Atlas Search Visual Editor.

  • To edit the raw index definition, select the Atlas Search JSON Editor.

5
  1. In the Index Name field, enter synonyms-tutorial.

    If you name your index default, you don't need to specify an index parameter in the $search pipeline stage. If you give a custom name to your index, you must specify this name in the index parameter.

  2. In the Database and Collection section, find the sample_mflix database, and select the movies collection.

6

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.

The following index definition specifies:

  • The language analyzer 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).

  1. Click Next.

  2. Click Refine Your Index.

  3. Click Add Field in the Field Mappings section.

  4. Click Customized Configuration.

  5. 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

    1. Click Add Data Type.

    2. Select String.

    3. 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.

  6. Click Add Synonym Mapping in the Synonym Mappings section.

  7. 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.

  8. Click Save Changes.

  1. Replace the default index definition with the following index definition.

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

The following index definition specifies:

  • The language analyzer lucene.standard 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.standard analyzer (including the title field, in this 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.standard analyzer (including the title field, in this example).

  1. Click Next.

  2. Click Refine Your Index.

  3. Click Add Field in the Field Mappings section.

  4. 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

    1. Select String.

    2. 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.

  5. Click Add Synonym Mapping in the Synonym Mappings section.

  6. 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.

  7. Click Add Synonym Mapping again in the Synonym Mappings section.

  8. 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.

  9. Click Save Changes.

  1. Replace the default index definition with the following index definition.

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

7
8

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

9

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.


Use the Select your language drop-down menu to set the language of the examples in this section.


Synonyms can be used only in queries that use the text operator. In this section, you connect to your Atlas 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
  1. If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.

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

  3. If it's not already displayed, click Clusters in the sidebar.

    The Clusters page displays.

2

You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.

  1. In the sidebar, click Atlas Search under the Services heading.

  2. From the Select data source dropdown, select your cluster and click Go to Atlas Search.

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3

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

4

Click Edit Query to view a default query syntax sample in JSON format.

5

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

The following queries:

  • Exclude all fields except the title field.

  • Add a field named score.

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

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.

[
{
$search: {
index: "synonyms-tutorial",
text: {
path: "title",
query: "automobile",
synonyms: "transportSynonyms"
}
}
}
]
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 Atlas 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. Atlas 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.

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

[
{
$search: {
index: "synonyms-tutorial",
text: {
path: "title",
query: "boat",
synonyms: "transportSynonyms"
}
}
}
]
SCORE: 5.373150825500488 _id: “573a13e9f29313caabdcd013”
plot: "A fearless sea captain sails a ship through loopholes in international…"
genres: Array
runtime: 90
...
title: "Vessel"
SCORE: 4.589139938354492 _id: “573a13e8f29313caabdc9e72”
countries: Array
genres: Array
runtime: 7
...
title: "Boats"
SCORE: 4.3452959060668945 _id: “573a1398f29313caabce90b6”
plot: "In 1914, a luxury ship leaves Italy in order to scatter the ashes of a…"
genres: Array
runtime: 128
...
title: "And the Ship Sails On"
SCORE: 4.3452959060668945 _id: “573a139cf29313caabcf7c75”
plot: "A young Pennsylvania man moves to Los Angeles to begin work for an amb…"
genres: Array
runtime: 90
...
title: "Broken Vessels"
SCORE: 4.3452959060668945 _id: “573a13f0f29313caabdda2dd”
plot: "A young man struggling with the death of his parents meets an extrover…"
genres: Array
runtime: 80
...
title: "Sailing to Paradise"
SCORE: 3.711261749267578 _id: “573a1397f29313caabce8796”
plot: "A Japanese photojournalist revisits Vietnam after the Liberation and l…"
genres: Array
runtime: 109
...
title: "Boat People"
SCORE: 3.711261749267578 _id: “573a13a6f29313caabd17a98”
plot: "Two straight men mistakenly end up on a "gays only" cruise."
genres: Array
runtime: 94
...
title: "Boat Trip"
SCORE: 3.1153182983398438 _id: “573a1394f29313caabce036c”
plot: "Three London gentlemen take vacation rowing down the Thames, encounter…"
genres: Array
runtime: 84
...
title: "Three Men in a Boat"
SCORE: 3.1153182983398438 _id: “573a1395f29313caabce2c28”
plot: "After a series of misunderstandings, the head of an aerospace research…"
genres: Array
runtime: 110
...
title: "The Glass Bottom Boat"
SCORE: 3.1153182983398438 _id: “573a13c2f29313caabd68772”
fullplot: "Jack is a shy and awkward man who drives a limo and lives an unassumin…"
imdb: Object
runtime: 2010
...
title: "Jack Goes Boating"

The Atlas Search results contain movies with boat, vessel, and sail in the title field because we configured boat, vessel, and sail to be synonyms of boat in the synonyms source collection named sample_synonyms, which is specified in the index for the collection.

Atlas Search returns the following documents only for a search of the word vessel in the results:

{ "title" : "Vessel", "score" : 5.373150825500488 }
{ "title" : "Broken Vessels", "score" : 4.3452959060668945 }

Atlas Search doesn't include documents with either boat or sail in the title field in the results because we didn't configure vessel to be a synonym of either boat or sail in the synonyms source collection. To test this, replace the value of the query field in the query above with vessel and run the query again.

Similarly, Atlas Search returns the following documents only in the results for a search of the term sail:

{ "title" : "And the Ship Sails On", "score" : 4.3452959060668945 }
{ "title" : "Sailing to Paradise", "score" : 4.3452959060668945 }

Atlas Search doesn't include documents with either boat or vessel in the title field in the results because we didn't configure sail to be a synonym of either boat or vessel in the synonyms source collection. To test this example, replace the value of the query field in the query above with sail and run the query again.

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

The 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. Also, the query searches the title field for attire and uses the attireSynonyms synonym mapping definition to search for the synonyms of attire that you configured in the attire_synonyms synonyms source collection.

[
{
$search: {
"index": "synonyms-tutorial",
"compound": {
"should": [{
"text": {
"path": "title",
"query": "automobile",
"synonyms": "transportSynonyms"
}
},
{
"text": {
"path": "title",
"query": "attire",
"synonyms": "attireSynonyms"
}
}]
}
}
}
]
SCORE: 4.812004089355469 _id: “573a139af29313caabcf003f”
plot: "The Dress is a tale filled with sex, violence, comedy and drama as it …"
genres: Array
runtime: 103
...
title: "The Dress"
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.891493320465088 _id: “573a1397f29313caabce77cd”
plot: "A mysterious blonde woman kills one of a psychiatrist's patients, and …"
genres: Array
runtime: 105
...
title: "Dressed to Kill"
SCORE: 3.891493320465088 _id: “573a13bcf29313caabd57e07”
fullplot: "Two things about Jane: she never says no to her friends (she's been a …"
imdb Object
year: 2008
...
title: "27 Dresses"
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"

The Atlas 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.

Atlas 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.

The query searches the title field for boat and uses the transportSynonyms synonym mapping definition to search for the synonyms of boat that you configured in the transport_synonyms synonyms source collection. Also, the query searches the title field for hat and uses the attireSynonyms synonym mapping definition to search for the synonyms of hat that you configured in the attire_synonyms synonyms source collection.

[
{
$search: {
index: "synonyms-tutorial",
compound: {
should: [{
text: {
path: "title",
query: "boat",
synonyms: "transportSynonyms"
}
},
{
text: {
path: "title",
query: "hat",
synonyms: "attireSynonyms"
}
}]
}
}
}
]
SCORE: 5.673145294189453 _id: “573a1397f29313caabce6bed”
plot: "Down-on-his-luck Hollywood producer Barry 'Dutch' Detweiler attempts t…"
genres: Array
runtime: 114
...
title: "Fedora"
SCORE: 5.373150825500488 _id: “573a13e9f29313caabdcd013”
plot: "A fearless sea captain sails a ship through loopholes in international…"
genres: Array
runtime: 90
...
title: "Vessel"
SCORE: 4.589139938354492 _id: “573a13e8f29313caabdc9e72”
countries: Array
genres: Array
runtime: 7
...
title: "Boats"
SCORE: 4.3452959060668945 _id: “573a1398f29313caabce90b6”
plot: "In 1914, a luxury ship leaves Italy in order to scatter the ashes of a…"
genres: Array
runtime: 128
...
title: "And the Ship Sails On"
SCORE: 4.3452959060668945 _id: “573a139cf29313caabcf7c75”
plot: "A young Pennsylvania man moves to Los Angeles to begin work for an amb…"
genres: Array
runtime: 90
...
title: "Broken Vessels"
SCORE: 4.3452959060668945 _id: “573a13f0f29313caabdda2dd”
plot: "A young man struggling with the death of his parents meets an extrover…"
genres: Array
runtime: 80
...
title: "Sailing to Paradise"
SCORE: 4.066137313842773 _id: “573a1392f29313caabcdaae8”
plot: "An American dancer comes to Britain and falls for a model whom he init…"
genres: Array
runtime: 101
...
title: "Top Hat"
SCORE: 4.066137313842773 _id: “573a1394f29313caabce05e8”
plot: "A Korean War veteran's morphine addiction wreaks havoc upon his family…"
genres: Array
runtime: 109
...
title: "A Hatful of Rain"
SCORE: 3.711261749267578 _id: “573a1397f29313caabce8796”
plot: "A Japanese photojournalist revisits Vietnam after the Liberation and l…"
genres: Array
runtime: 109
...
title: "Boat People"
SCORE: 3.711261749267578 _id: “573a13a6f29313caabd17a98”
plot: "Two straight men mistakenly end up on a "gays only" cruise."
genres: Array
runtime: 94
...
title: "Boat Trip"

The Atlas Search results contain documents for both the search terms. The results contain movies with vessel, boat, and sail in the title field for the query term boat because we configured boat to be a synonym of boat, vessel, and sail in the synonyms source collection named transport_synonyms.

Atlas Search doesn't include documents with either boat or sail in the title field in the results for a search of the term vessel because we didn't configure vessel to be a synonym of either boat or sail in the synonyms source collection. Similary, Atlas Search doesn't include documents with either boat or vessel in the title field in the results for a search of the term sail because we didn't configure sail to be a synonym of either boat or vessel in the synonyms source collection. To test these examples, replace the value of the query field in the query above with vessel or sail and run the query again.

The result also contains movies with fedora and hat in the title field for the query term hat because we configured hat to be a synonym of hat, fedora, and headgear in the synonyms source collection named attire_synonyms.

Atlas Search doesn't include documents with either hat or fedora in the title field in the results for a search of the term headgear because we didn't configure headgear to be a synonym of either hat or fedora in the synonyms source collection. Similary, Atlas Search doesn't include documents with either hat or headgear in the title field in the results for a search of the term fedora because we didn't configure fedora to be a synonym of either hat or headgear in the synonyms source collection. To test these examples, replace the value of the query field in the query above with fedora or headgear and run the query again.

6

The Search Tester might not display all the fields in the documents it returns. To view all the fields, including the field that you specify in the query path, expand the document in the results.

1

Open mongosh in a terminal window and connect to your cluster. For detailed instructions on connecting, see Connect via mongosh.

2

Run the following command at mongosh prompt:

use sample_mflix
3

If you created an index with a single synonym mapping definition, run the query in the Simple Example tab below. If you defined multiple synonym mappings in your index, you can run the queries in both the tabs below.

These queries use the following pipeline stages:

  • $search stage to search the collection.

  • $limit stage to limit the output to 10 results.

  • $project stage to:

    • Exclude all fields except the title field.

    • Add a field named score.

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

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.

db.movies.aggregate([
{
$search: {
"index": "synonyms-tutorial",
"text": {
"path": "title",
"query": "automobile",
"synonyms": "transportSynonyms"
}
}
},
{
$limit: 10
},
{
$project: {
"_id": 0,
"title": 1,
"score": { $meta: "searchScore" }
}
}
])
{ "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 Atlas 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. Atlas 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.

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

db.movies.aggregate([
{
$search: {
"index": "synonyms-tutorial",
"text": {
"path": "title",
"query": "boat",
"synonyms": "transportSynonyms"
}
}
},
{
$limit: 10
},
{
$project: {
"_id": 0,
"title": 1,
"score": { $meta: "searchScore" }
}
}
])
{ "title" : "Vessel", "score" : 5.373150825500488 }
{ "title" : "Boats", "score" : 4.589139938354492 }
{ "title" : "And the Ship Sails On", "score" : 4.3452959060668945 }
{ "title" : "Broken Vessels", "score" : 4.3452959060668945 }
{ "title" : "Sailing to Paradise", "score" : 4.3452959060668945 }
{ "title" : "Boat People", "score" : 3.711261749267578 }
{ "title" : "Boat Trip", "score" : 3.711261749267578 }
{ "title" : "Three Men in a Boat", "score" : 3.1153182983398438 }
{ "title" : "The Glass Bottom Boat", "score" : 3.1153182983398438 }
{ "title" : "Jack Goes Boating", "score" : 3.1153182983398438 }

The Atlas Search results contain movies with boat, vessel, and sail in the title field because we configured boat, vessel, and sail to be synonyms of boat in the synonyms source collection named sample_synonyms, which is specified in the index for the collection.

Atlas Search returns the following documents only for a search of the word vessel in the results:

{ "title" : "Vessel", "score" : 5.373150825500488 }
{ "title" : "Broken Vessels", "score" : 4.3452959060668945 }

Atlas Search doesn't include documents with either boat or sail in the title field in the results because we didn't configure vessel to be a synonym of either boat or sail in the synonyms source collection. To test this, replace the value of the query field in the query above with vessel and run the query again.

Similarly, Atlas Search returns the following documents only in the results for a search of the term sail:

{ "title" : "And the Ship Sails On", "score" : 4.3452959060668945 }
{ "title" : "Sailing to Paradise", "score" : 4.3452959060668945 }

Atlas Search doesn't include documents with either boat or vessel in the title field in the results because we didn't configure sail to be a synonym of either boat or vessel in the synonyms source collection. To test this example, replace the value of the query field in the query above with sail and run the query again.

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

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.

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" }
}
}
])
[
{ 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 Atlas 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.

Atlas 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.

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

db.movies.aggregate([
{
$search: {
"index": "synonyms-tutorial",
"compound": {
"should": [{
"text": {
"path": "title",
"query": "boat",
"synonyms": "transportSynonyms"
}
},
{
"text": {
"path": "title",
"query": "hat",
"synonyms": "attireSynonyms"
}
}]
}
}
},
{
$limit: 10
},
{
$project: {
"_id": 0,
"title": 1,
"score": { $meta: "searchScore" }
}
}
])
[
{ title: 'Fedora', score: 5.673145294189453 },
{ title: 'Vessel', score: 5.373150825500488 },
{ title: 'Boats', score: 4.589139938354492 },
{ title: 'And the Ship Sails On', score: 4.3452959060668945 },
{ title: 'Broken Vessels', score: 4.3452959060668945 },
{ title: 'Sailing to Paradise', score: 4.3452959060668945 },
{ title: 'Top Hat', score: 4.066137313842773 },
{ title: 'A Hatful of Rain', score: 4.066137313842773 },
{ title: 'Boat People', score: 3.711261749267578 },
{ title: 'Boat Trip', score: 3.711261749267578 }
]

The Atlas Search results contain documents for both the search terms. The results contain movies with vessel, boat, and sail in the title field for the query term boat because we configured boat to be a synonym of boat, vessel, and sail in the synonyms source collection named transport_synonyms.

Atlas Search doesn't include documents with either boat or sail in the title field in the results for a search of the term vessel because we didn't configure vessel to be a synonym of either boat or sail in the synonyms source collection. Similary, Atlas Search doesn't include documents with either boat or vessel in the title field in the results for a search of the term sail because we didn't configure sail to be a synonym of either boat or vessel in the synonyms source collection. To test these examples, replace the value of the query field in the query above with vessel or sail and run the query again.

The result also contains movies with fedora and hat in the title field for the query term hat because we configured hat to be a synonym of hat, fedora, and headgear in the synonyms source collection named attire_synonyms.

Atlas Search doesn't include documents with either hat or fedora in the title field in the results for a search of the term headgear because we didn't configure headgear to be a synonym of either hat or fedora in the synonyms source collection. Similary, Atlas Search doesn't include documents with either hat or headgear in the title field in the results for a search of the term fedora because we didn't configure fedora to be a synonym of either hat or headgear in the synonyms source collection. To test these examples, replace the value of the query field in the query above with fedora or headgear and run the query again.

1

Open MongoDB Compass and connect to your cluster. For detailed instructions on connecting, see Connect via Compass.

2

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

3

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

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 stage to limit the output to 10 results

  • $project stage to exclude all fields except title and add a field named score

To run this query in MongoDB Compass:

  1. Click the Aggregations tab.

  2. 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 Auto Preview, MongoDB Compass displays the following documents next to the $project pipeline stage:

    {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 Atlas 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. Atlas 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.

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

  • $limit stage to limit the output to 10 results

  • $project stage to exclude all fields except title and add a field named score

To run this query in MongoDB Compass:

  1. Click the Aggregations tab.

  2. 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": "boat",
    "synonyms": "transportSynonyms"
    }
    }

    $limit

    10

    $project

    {
    "_id": 0,
    "title": 1,
    "score": { "$meta": "searchScore" }
    }

    If you enabled Auto Preview, MongoDB Compass displays the following documents next to the $project pipeline stage:

    {title Vessel} {score 5.373150825500488}
    {title Boats} {score 4.589139938354492}
    {title And the Ship Sails On} {score 4.3452959060668945}
    {title Broken Vessels} {score 4.3452959060668945}
    {title Sailing to Paradise} {score 4.3452959060668945}
    {title Boat People} {score 3.711261749267578}
    {title Boat Trip} {score 3.711261749267578}
    {title Three Men in a Boat} {score 3.1153182983398438}
    {title The Glass Bottom Boat} {score 3.1153182983398438}
    {title Jack Goes Boating} {score 3.1153182983398438}

    The Atlas Search results contain movies with boat, vessel, and sail in the title field because we configured boat, vessel, and sail to be synonyms of boat in the synonyms source collection named sample_synonyms, which is specified in the index for the collection.

    Atlas Search returns the following documents only for a search of the word vessel in the results:

    { "title" : "Vessel", "score" : 5.373150825500488 }
    { "title" : "Broken Vessels", "score" : 4.3452959060668945 }

    Atlas Search doesn't include documents with either boat or sail in the title field in the results because we didn't configure vessel to be a synonym of either boat or sail in the synonyms source collection. To test this, replace the value of the query field in the query above with vessel and run the query again.

    Similarly, Atlas Search returns the following documents only in the results for a search of the term sail:

    { "title" : "And the Ship Sails On", "score" : 4.3452959060668945 }
    { "title" : "Sailing to Paradise", "score" : 4.3452959060668945 }

    Atlas Search doesn't include documents with either boat or vessel in the title field in the results because we didn't configure sail to be a synonym of either boat or vessel in the synonyms source collection. To test this example, replace the value of the query field in the query above with sail and run the query again.

4

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

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 stage to limit the output to 10 results

  • $project stage to exclude all fields except title and add a field named score

To run this query in MongoDB Compass:

  1. Click the Aggregations tab.

  2. 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 Auto Preview, MongoDB Compass displays the following documents next to the $project pipeline stage:

    { 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 Atlas 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.

    Atlas 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.

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

The query includes the following stages:

  • $limit stage to limit the output to 10 results

  • $project stage to exclude all fields except title and add a field named score

To run this query in MongoDB Compass:

  1. Click the Aggregations tab.

  2. 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": "boat",
    "synonyms": "transportSynonyms"
    }
    },
    {
    "text": {
    "path": "title",
    "query": "hat",
    "synonyms": "attireSynonyms"
    }
    }]
    }
    }

    $limit

    10

    $project

    {
    "_id": 0,
    "title": 1,
    "score": { "$meta": "searchScore" }
    }

    If you enabled Auto Preview, MongoDB Compass displays the following documents next to the $project pipeline stage:

    { title: 'Fedora', score: 5.673145294189453 },
    { title: 'Vessel', score: 5.373150825500488 },
    { title: 'Boats', score: 4.589139938354492 },
    { title: 'And the Ship Sails On', score: 4. 3452959060668945 },
    { title: 'Broken Vessels', score: 4.3452959060668945 },
    { title: 'Sailing to Paradise', score: 4.3452959060668945 },
    { title: 'Top Hat', score: 4.066137313842773 },
    { title: 'A Hatful of Rain', score: 4.066137313842773 },
    { title: 'Boat People', score: 3.711261749267578 },
    { title: 'Boat Trip', score: 3.711261749267578 }

    The Atlas Search results contain documents for both the search terms. The results contain movies with vessel, boat, and sail in the title field for the query term boat because we configured boat to be a synonym of boat, vessel, and sail in the synonyms source collection named transport_synonyms.

    Atlas Search doesn't include documents with either boat or sail in the title field in the results for a search of the term vessel because we didn't configure vessel to be a synonym of either boat or sail in the synonyms source collection. Similary, Atlas Search doesn't include documents with either boat or vessel in the title field in the results for a search of the term sail because we didn't configure sail to be a synonym of either boat or vessel in the synonyms source collection. To test these examples, replace the value of the query field in the query above with vessel or sail and run the query again.

    The result also contains movies with fedora and hat in the title field for the query term hat because we configured hat to be a synonym of hat, fedora, and headgear in the synonyms source collection named attire_synonyms.

    Atlas Search doesn't include documents with either hat or fedora in the title field in the results for a search of the term headgear because we didn't configure headgear to be a synonym of either hat or fedora in the synonyms source collection. Similary, Atlas Search doesn't include documents with either hat or headgear in the title field in the results for a search of the term fedora because we didn't configure fedora to be a synonym of either hat or headgear in the synonyms source collection. To test these examples, replace the value of the query field in the query above with fedora or headgear and run the query again.

1

These code examples perform the following tasks:

  • Imports mongodb packages and dependencies.

  • Establishes a connection to your Atlas cluster.

  • Iterates over the cursor to print the documents that match the query.

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

  1. Create a file named synonyms-equivalent-query.go.

  2. Copy and paste the code example into the synonyms-equivalent-query.go file.

    The code example contains the following stages:

    • $search stage to search 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.

    • $limit stage to limit the output to 10 results.

    • $project stage to exclude all fields except title and add a field named score.

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/bson"
    9 "go.mongodb.org/mongo-driver/mongo"
    10 "go.mongodb.org/mongo-driver/mongo/options"
    11)
    12
    13// define structure of movies collection
    14type MovieCollection struct {
    15 title string `bson:"Title,omitempty"`
    16}
    17
    18func main() {
    19 var err error
    20 // connect to the Atlas cluster
    21 ctx := context.Background()
    22 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
    23 if err != nil {
    24 panic(err)
    25 }
    26 defer client.Disconnect(ctx)
    27 // set namespace
    28 collection := client.Database("sample_mflix").Collection("movies")
    29 // define pipeline
    30 searchStage := bson.D{{"$search", bson.D{{"index", "synonyms-tutorial"}, {"text", bson.D{{"path", "title"}, {"query", "automobile"}, {"synonyms", "transportSynonyms"}}}}}}
    31 limitStage := bson.D{{"$limit", 10}}
    32 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
    33 // specify the amount of time the operation can run on the server
    34 opts := options.Aggregate().SetMaxTime(5 * time.Second)
    35 // run pipeline
    36 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
    37 if err != nil {
    38 panic(err)
    39 }
    40 // print results
    41 var results []bson.D
    42 if err = cursor.All(context.TODO(), &results); err != nil {
    43 panic(err)
    44 }
    45 for _, result := range results {
    46 fmt.Println(result)
    47 }
    48}
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Run the following command to query your collection:

    go run synonyms-equivalent-query.go

    When you run synonyms-equivalent-query.go, the program prints the following documents to your terminal:

    [{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 Atlas 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. Atlas 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. Create a file named synonyms-explicit-query.go.

  2. Copy and paste the code example into the synonyms-explicit-query.go file.

    The code example contains the following stages:

    • $search stage to search the title field for the word boat and uses the synonym mapping definition named transportSynonyms to search for words configured as synonyms of the query word boat in the synonyms source collection named transport_synonyms.

    • $limit stage to limit the output to 10 results.

    • $project stage to exclude all fields except title and add a field named score.

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/bson"
    9 "go.mongodb.org/mongo-driver/mongo"
    10 "go.mongodb.org/mongo-driver/mongo/options"
    11)
    12
    13// define structure of movies collection
    14type MovieCollection struct {
    15 title string `bson:"Title,omitempty"`
    16}
    17
    18func main() {
    19 var err error
    20 // connect to the Atlas cluster
    21 ctx := context.Background()
    22 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
    23 if err != nil {
    24 panic(err)
    25 }
    26 defer client.Disconnect(ctx)
    27 // set namespace
    28 collection := client.Database("sample_mflix").Collection("movies")
    29 // define pipeline
    30 searchStage := bson.D{{"$search", bson.D{{"text", bson.D{{"index", "synonyms-tutorial"}, {"path", "title"}, {"query", "boat"}, {"synonyms", "transportSynonyms"}}}}}}
    31 limitStage := bson.D{{"$limit", 10}}
    32 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
    33 // specify the amount of time the operation can run on the server
    34 opts := options.Aggregate().SetMaxTime(5 * time.Second)
    35 // run pipeline
    36 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
    37 if err != nil {
    38 panic(err)
    39 }
    40 // print results
    41 var results []bson.D
    42 if err = cursor.All(context.TODO(), &results); err != nil {
    43 panic(err)
    44 }
    45 for _, result := range results {
    46 fmt.Println(result)
    47 }
    48}
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Run the following command to query your collection:

    go run synonyms-explicit-query.go
    [{title Vessel} {score 5.373150825500488}]
    [{title Boats} {score 4.589139938354492}]
    [{title And the Ship Sails On} {score 4.3452959060668945}]
    [{title Broken Vessels} {score 4.3452959060668945}]
    [{title Sailing to Paradise} {score 4.3452959060668945}]
    [{title Boat People} {score 3.711261749267578}]
    [{title Boat Trip} {score 3.711261749267578}]
    [{title Three Men in a Boat} {score 3.1153182983398438}]
    [{title The Glass Bottom Boat} {score 3.1153182983398438}]
    [{title Jack Goes Boating} {score 3.1153182983398438}]

    The Atlas Search results contain movies with boat, vessel, and sail in the title field because we configured boat, vessel, and sail to be synonyms of boat in the synonyms source collection named sample_synonyms, which is specified in the index for the collection.

    Atlas Search returns the following documents only for a search of the word vessel in the results:

    { "title" : "Vessel", "score" : 5.373150825500488 }
    { "title" : "Broken Vessels", "score" : 4.3452959060668945 }

    Atlas Search doesn't include documents with either boat or sail in the title field in the results because we didn't configure vessel to be a synonym of either boat or sail in the synonyms source collection. To test this, replace the value of the query field in the query above with vessel and run the query again.

    Similarly, Atlas Search returns the following documents only in the results for a search of the term sail:

    { "title" : "And the Ship Sails On", "score" : 4.3452959060668945 }
    { "title" : "Sailing to Paradise", "score" : 4.3452959060668945 }

    Atlas Search doesn't include documents with either boat or vessel in the title field in the results because we didn't configure sail to be a synonym of either boat or vessel in the synonyms source collection. To test this example, replace the value of the query field in the query above with sail and run the query again.

2

These code examples perform the following tasks:

  • Imports mongodb packages and dependencies.

  • Establishes a connection to your Atlas cluster.

  • Iterates over the cursor to print the documents that match the query.

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

  1. Create a file named synonyms-equivalent-query.go.

  2. Copy and paste the code example into the synonyms-equivalent-query.go file.

    The code example contains the following stages:

    • $search stage to search 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.

    • $limit stage to limit the output to 10 results.

    • $project stage to exclude all fields except title and add a field named score.

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/bson"
    9 "go.mongodb.org/mongo-driver/mongo"
    10 "go.mongodb.org/mongo-driver/mongo/options"
    11)
    12
    13// define structure of movies collection
    14type MovieCollection struct {
    15 title string `bson:"Title,omitempty"`
    16}
    17
    18func main() {
    19 var err error
    20 // connect to the Atlas cluster
    21 ctx := context.Background()
    22 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
    23 if err != nil {
    24 panic(err)
    25 }
    26 defer client.Disconnect(ctx)
    27 // set namespace
    28 collection := client.Database("sample_mflix").Collection("movies")
    29 // define pipeline
    30 searchStage := bson.D{{"$search", bson.M{
    31 "index": "synonyms-tutorial",
    32 "compound": bson.M{
    33 "should": bson.A{
    34 bson.M{
    35 "text": bson.D{
    36 {"path", "title"}, {"query", "automobile"}, {"synonyms", "transportSynonyms"},
    37 },
    38 },
    39 bson.M{
    40 "text": bson.D{
    41 {"path", "title"}, {"query", "attire"}, {"synonyms", "attireSynonyms"},
    42 },
    43 },
    44 },
    45 },
    46 }}}
    47 limitStage := bson.D{{"$limit", 10}}
    48 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
    49 // specify the amount of time the operation can run on the server
    50 opts := options.Aggregate().SetMaxTime(5 * time.Second)
    51 // run pipeline
    52 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
    53 if err != nil {
    54 panic(err)
    55 }
    56 // print results
    57 var results []bson.D
    58 if err = cursor.All(context.TODO(), &results); err != nil {
    59 panic(err)
    60 }
    61 for _, result := range results {
    62 fmt.Println(result)
    63 }
    64}
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Run the following command to query your collection:

    go run synonyms-equivalent-query.go
    [{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 Atlas 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.

    Atlas 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.

  1. Create a file named synonyms-explicit-query.go.

  2. Copy and paste the code example into the synonyms-explicit-query.go file.

    The code example contains the following stages:

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

    • $limit stage to limit the output to 10 results.

    • $project stage to exclude all fields except title and add a field named score.

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/bson"
    9 "go.mongodb.org/mongo-driver/mongo"
    10 "go.mongodb.org/mongo-driver/mongo/options"
    11)
    12
    13// define structure of movies collection
    14type MovieCollection struct {
    15 title string `bson:"Title,omitempty"`
    16}
    17
    18func main() {
    19 var err error
    20 // connect to the Atlas cluster
    21 ctx := context.Background()
    22 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
    23 if err != nil {
    24 panic(err)
    25 }
    26 defer client.Disconnect(ctx)
    27 // set namespace
    28 collection := client.Database("sample_mflix").Collection("movies")
    29 // define pipeline
    30 searchStage := bson.D{{"$search", bson.M{
    31 "index": "synonyms-tutorial",
    32 "compound": bson.M{
    33 "must": bson.A{
    34 bson.M{
    35 "text": bson.D{
    36 {"path", "title"}, {"query", "boat"}, {"synonyms", "transportSynonyms"},
    37 },
    38 },
    39 bson.M{
    40 "text": bson.D{
    41 {"path", "title"}, {"query", "hat"}, {"synonyms", "attireSynonyms"},
    42 },
    43 },
    44 },
    45 },
    46 }}}
    47 limitStage := bson.D{{"$limit", 10}}
    48 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
    49 // specify the amount of time the operation can run on the server
    50 opts := options.Aggregate().SetMaxTime(5 * time.Second)
    51 // run pipeline
    52 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
    53 if err != nil {
    54 panic(err)
    55 }
    56 // print results
    57 var results []bson.D
    58 if err = cursor.All(context.TODO(), &results); err != nil {
    59 panic(err)
    60 }
    61 for _, result := range results {
    62 fmt.Println(result)
    63 }
    64}
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Run the following command to query your collection:

    go run synonyms-explicit-query.go
    [{title Fedora} {score 5.673145294189453}]
    [{title Vessel} {score 5.373150825500488}]
    [{title Boats} {score 4.589139938354492}]
    [{title And the Ship Sails On} {score 4.3452959060668945}]
    [{title Broken Vessels} {score 4.3452959060668945}]
    [{title Sailing to Paradise} {score 4.3452959060668945}]
    [{title Top Hat} {score 4.066137313842773}]
    [{title A Hatful of Rain} {score 4.066137313842773}]
    [{title Boat People} {score 3.711261749267578}]
    [{title Boat Trip} {score 3.711261749267578}]

    The Atlas Search results contain documents for both the search terms. The results contain movies with vessel, boat, and sail in the title field for the query term boat because we configured boat to be a synonym of boat, vessel, and sail in the synonyms source collection named transport_synonyms.

    Atlas Search doesn't include documents with either boat or sail in the title field in the results for a search of the term vessel because we didn't configure vessel to be a synonym of either boat or sail in the synonyms source collection. Similary, Atlas Search doesn't include documents with either boat or vessel in the title field in the results for a search of the term sail because we didn't configure sail to be a synonym of either boat or vessel in the synonyms source collection. To test these examples, replace the value of the query field in the query above with vessel or sail and run the query again.

    The result also contains movies with fedora and hat in the title field for the query term hat because we configured hat to be a synonym of hat, fedora, and headgear in the synonyms source collection named attire_synonyms.

    Atlas Search doesn't include documents with either hat or fedora in the title field in the results for a search of the term headgear because we didn't configure headgear to be a synonym of either hat or fedora in the synonyms source collection. Similary, Atlas Search doesn't include documents with either hat or headgear in the title field in the results for a search of the term fedora because we didn't configure fedora to be a synonym of either hat or headgear in the synonyms source collection. To test these examples, replace the value of the query field in the query above with fedora or headgear and run the query again.

1

junit

4.11 or higher version

mongodb-driver-sync

4.3.0 or higher version

slf4j-log4j12

1.7.30 or higher version

2

These code examples perform the following tasks:

  • Imports mongodb packages and dependencies.

  • Establishes a connection to your Atlas cluster.

  • Iterates over the cursor to print the documents that match the query.

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

  1. Create a file named SynonymsEquivalentQuery.java.

  2. Copy and paste the following code into the file.

    The code example contains the following stages:

    • $search stage to search 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.

    • $limit stage to limit the output to 10 results.

    • $project stage to exclude all fields except title and add a field named score.

    1import java.util.Arrays;
    2import static com.mongodb.client.model.Filters.eq;
    3import static com.mongodb.client.model.Aggregates.limit;
    4import static com.mongodb.client.model.Aggregates.project;
    5import static com.mongodb.client.model.Projections.excludeId;
    6import static com.mongodb.client.model.Projections.fields;
    7import static com.mongodb.client.model.Projections.include;
    8import static com.mongodb.client.model.Projections.computed;
    9import com.mongodb.client.MongoClient;
    10import com.mongodb.client.MongoClients;
    11import com.mongodb.client.MongoCollection;
    12import com.mongodb.client.MongoDatabase;
    13import org.bson.Document;
    14
    15public class SynonymsEquivalentQuery {
    16 public static void main( String[] args ) {
    17 // define query
    18 Document agg = new Document("$search",
    19 new Document("index", "synonyms-tutorial")
    20 .append("text",
    21 new Document("query", "automobile")
    22 .append("path","title")
    23 .append("synonyms", "transportSynonyms")));
    24
    25 // specify connection
    26 String uri = "<connection-string>";
    27
    28 // establish connection and set namespace
    29 try (MongoClient mongoClient = MongoClients.create(uri)) {
    30 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    31 MongoCollection<Document> collection = database.getCollection("movies");
    32
    33 // run query and print results
    34 collection.aggregate(Arrays.asList(agg,
    35 limit(10),
    36 project(fields(excludeId(), include("title"), computed("score", new Document("$meta", "searchScore")))))
    37 ).forEach(doc -> System.out.println(doc.toJson()));
    38 }
    39 }
    40}

    Note

    To run the sample code in your Maven environment, add the following above the import statements in your file.

    package com.mongodb.drivers;
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Compile and run SynonymsEquivalentQuery.java file.

    javac SynonymsEquivalentQuery.java
    java SynonymsEquivalentQuery
    {"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 Atlas 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. Atlas 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. Create a file named SynonymsExplicitQuery.java.

  2. Copy and paste the following code into the file.

    The code example contains the following stages:

    • $search stage to search the title field for the word boat and uses the synonym mapping definition named transportSynonyms to search for words configured as synonyms of the query word boat in the synonyms source collection named transport_synonyms.

    • $limit stage to limit the output to 10 results.

    • $project stage to exclude all fields except title and add a field named score.

    1import java.util.Arrays;
    2import static com.mongodb.client.model.Filters.eq;
    3import static com.mongodb.client.model.Aggregates.limit;
    4import static com.mongodb.client.model.Aggregates.project;
    5import static com.mongodb.client.model.Projections.excludeId;
    6import static com.mongodb.client.model.Projections.fields;
    7import static com.mongodb.client.model.Projections.include;
    8import static com.mongodb.client.model.Projections.computed;
    9import com.mongodb.client.MongoClient;
    10import com.mongodb.client.MongoClients;
    11import com.mongodb.client.MongoCollection;
    12import com.mongodb.client.MongoDatabase;
    13import org.bson.Document;
    14
    15public class SynonymsExplicitQuery {
    16 public static void main( String[] args ) {
    17 // define query
    18 Document agg = new Document("$search",
    19 new Document("index", "synonyms-tutorial")
    20 .append("text",
    21 new Document("query", "boat")
    22 .append("path","title")
    23 .append("synonyms", "transportSynonyms")));
    24
    25 // specify connection
    26 String uri = "<connection-string>";
    27
    28 // establish connection and set namespace
    29 try (MongoClient mongoClient = MongoClients.create(uri)) {
    30 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    31 MongoCollection<Document> collection = database.getCollection("movies");
    32
    33 // run query and print results
    34 collection.aggregate(Arrays.asList(agg,
    35 limit(10),
    36 project(fields(excludeId(), include("title"), computed("score", new Document("$meta", "searchScore")))))
    37 ).forEach(doc -> System.out.println(doc.toJson()));
    38 }
    39 }
    40}

    Note

    To run the sample code in your Maven environment, add the following above the import statements in your file.

    package com.mongodb.drivers;
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Compile and run SynonymsExplicitQuery.java file.

    javac SynonymsExplicitQuery.java
    java SynonymsExplicitQuery
    {"title": "Vessel", "score": 5.373150825500488}
    {"title": "Boats", "score": 4.589139938354492}
    {"title": "And the Ship Sails On", "score": 4.3452959060668945}
    {"title": "Broken Vessels", "score": 4.3452959060668945}
    {"title": "Sailing to Paradise", "score": 4.3452959060668945}
    {"title": "Boat People", "score": 3.711261749267578}
    {"title": "Boat Trip", "score": 3.711261749267578}
    {"title": "Three Men in a Boat", "score": 3.1153182983398438}
    {"title": "The Glass Bottom Boat", "score": 3.1153182983398438}
    {"title": "Jack Goes Boating", "score": 3.1153182983398438}

    The Atlas Search results contain movies with boat, vessel, and sail in the title field because we configured boat, vessel, and sail to be synonyms of boat in the synonyms source collection named sample_synonyms, which is specified in the index for the collection.

    Atlas Search returns the following documents only for a search of the word vessel in the results:

    { "title" : "Vessel", "score" : 5.373150825500488 }
    { "title" : "Broken Vessels", "score" : 4.3452959060668945 }

    Atlas Search doesn't include documents with either boat or sail in the title field in the results because we didn't configure vessel to be a synonym of either boat or sail in the synonyms source collection. To test this, replace the value of the query field in the query above with vessel and run the query again.

    Similarly, Atlas Search returns the following documents only in the results for a search of the term sail:

    { "title" : "And the Ship Sails On", "score" : 4.3452959060668945 }
    { "title" : "Sailing to Paradise", "score" : 4.3452959060668945 }

    Atlas Search doesn't include documents with either boat or vessel in the title field in the results because we didn't configure sail to be a synonym of either boat or vessel in the synonyms source collection. To test this example, replace the value of the query field in the query above with sail and run the query again.

3

These code examples perform the following tasks:

  • Imports mongodb packages and dependencies.

  • Establishes a connection to your Atlas cluster.

  • Iterates over the cursor to print the documents that match the query.

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

  1. Create a file named SynonymsEquivalentQuery.java.

  2. Copy and paste the following code into the file.

    The code example contains the following stages:

    • $search stage to search 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.

    • $limit stage to limit the output to 10 results.

    • $project stage to exclude all fields except title and add a field named score.

    1import java.util.Arrays;
    2import static com.mongodb.client.model.Filters.eq;
    3import static com.mongodb.client.model.Aggregates.limit;
    4import static com.mongodb.client.model.Aggregates.project;
    5import static com.mongodb.client.model.Projections.computed;
    6import static com.mongodb.client.model.Projections.excludeId;
    7import static com.mongodb.client.model.Projections.fields;
    8import static com.mongodb.client.model.Projections.include;
    9import com.mongodb.client.MongoClient;
    10import com.mongodb.client.MongoClients;
    11import com.mongodb.client.MongoCollection;
    12import com.mongodb.client.MongoDatabase;
    13import org.bson.Document;
    14
    15public class SynonymsEquivalentQuery {
    16 public static void main( String[] args ) {
    17 Document agg = new Document("$search",
    18 new Document("index", "synonyms-tutorial")
    19 .append("compound",
    20 new Document("should", Arrays.asList(new Document("text",
    21 new Document("path", "title")
    22 .append("query", "automobile")
    23 .append("synonyms", "transportSynonyms")),
    24 new Document("text",
    25 new Document("path", "title")
    26 .append("query", "attire")
    27 .append("synonyms", "attireSynonyms"))))));
    28
    29 String uri = "<connection-string>";
    30
    31 try (MongoClient mongoClient = MongoClients.create(uri)) {
    32 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    33 MongoCollection<Document> collection = database.getCollection("movies");
    34
    35 collection.aggregate(Arrays.asList(agg,
    36 limit(10),
    37 project(fields(excludeId(), include("title"), computed("score", new Document("$meta", "searchScore")))))
    38 ).forEach(doc -> System.out.println(doc.toJson()));
    39 }
    40 }
    41}

    Note

    To run the sample code in your Maven environment, add the following above the import statements in your file.

    package com.mongodb.drivers;
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Compile and run SynonymsEquivalentQuery.java file.

    javac SynonymsEquivalentQuery.java
    java SynonymsEquivalentQuery
    {"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 Atlas 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.

    Atlas 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.

  1. Create a file named SynonymsExplicitQuery.java.

  2. Copy and paste the following code into the file.

    The code example contains the following stages:

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

    • $limit stage to limit the output to 10 results.

    • $project stage to exclude all fields except title and add a field named score.

    1import java.util.Arrays;
    2import static com.mongodb.client.model.Filters.eq;
    3import static com.mongodb.client.model.Aggregates.limit;
    4import static com.mongodb.client.model.Aggregates.project;
    5import static com.mongodb.client.model.Projections.computed;
    6import static com.mongodb.client.model.Projections.excludeId;
    7import static com.mongodb.client.model.Projections.fields;
    8import static com.mongodb.client.model.Projections.include;
    9import com.mongodb.client.MongoClient;
    10import com.mongodb.client.MongoClients;
    11import com.mongodb.client.MongoCollection;
    12import com.mongodb.client.MongoDatabase;
    13import org.bson.Document;
    14
    15public class SynonymsExplicitQuery {
    16 public static void main( String[] args ) {
    17 Document agg = new Document("$search",
    18 new Document("index", "synonyms-tutorial")
    19 .append("compound",
    20 new Document("should", Arrays.asList(new Document("text",
    21 new Document("path", "title")
    22 .append("query", "boat")
    23 .append("synonyms", "transportSynonyms")),
    24 new Document("text",
    25 new Document("path", "title")
    26 .append("query", "hat")
    27 .append("synonyms", "attireSynonyms"))))));
    28
    29 String uri = "<connection-string>";
    30
    31 try (MongoClient mongoClient = MongoClients.create(uri)) {
    32 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    33 MongoCollection<Document> collection = database.getCollection("movies");
    34
    35 collection.aggregate(Arrays.asList(agg,
    36 limit(10),
    37 project(fields(excludeId(), include("title"), computed("score", new Document("$meta", "searchScore")))))
    38 ).forEach(doc -> System.out.println(doc.toJson()));
    39 }
    40 }
    41}

    Note

    To run the sample code in your Maven environment, add the following above the import statements in your file.

    package com.mongodb.drivers;
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Compile and run SynonymsExplicitQuery.java file.

    javac SynonymsExplicitQuery.java
    java SynonymsExplicitQuery
    {"title": "Fedora", "score": 5.673145294189453}
    {"title": "Vessel", "score": 5.373150825500488}
    {"title": "Boats", "score": 4.589139938354492}
    {"title": "And the Ship Sails On", "score": 4.3452959060668945}
    {"title": "Broken Vessels", "score": 4.3452959060668945}
    {"title": "Sailing to Paradise", "score": 4.3452959060668945}
    {"title": "Top Hat", "score": 4.066137313842773}
    {"title": "A Hatful of Rain", "score": 4.066137313842773}
    {"title": "Boat People", "score": 3.711261749267578}
    {"title": "Boat Trip", "score": 3.711261749267578}

    The Atlas Search results contain documents for both the search terms. The results contain movies with vessel, boat, and sail in the title field for the query term boat because we configured boat to be a synonym of boat, vessel, and sail in the synonyms source collection named transport_synonyms.

    Atlas Search doesn't include documents with either boat or sail in the title field in the results for a search of the term vessel because we didn't configure vessel to be a synonym of either boat or sail in the synonyms source collection. Similary, Atlas Search doesn't include documents with either boat or vessel in the title field in the results for a search of the term sail because we didn't configure sail to be a synonym of either boat or vessel in the synonyms source collection. To test these examples, replace the value of the query field in the query above with vessel or sail and run the query again.

    The result also contains movies with fedora and hat in the title field for the query term hat because we configured hat to be a synonym of hat, fedora, and headgear in the synonyms source collection named attire_synonyms.

    Atlas Search doesn't include documents with either hat or fedora in the title field in the results for a search of the term headgear because we didn't configure headgear to be a synonym of either hat or fedora in the synonyms source collection. Similary, Atlas Search doesn't include documents with either hat or headgear in the title field in the results for a search of the term fedora because we didn't configure fedora to be a synonym of either hat or headgear in the synonyms source collection. To test these examples, replace the value of the query field in the query above with fedora or headgear and run the query again.

1

mongodb-driver-kotlin-coroutine

4.10.0 or higher version

2

These code examples perform the following tasks:

  • Imports mongodb packages and dependencies.

  • Establishes a connection to your Atlas cluster.

  • Prints the documents that match the query from the AggregateFlow instance.

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

  1. Create a file named SynonymsEquivalentQuery.kt.

  2. Copy and paste the following code into the file.

    The code example contains the following stages:

    • $search stage to search 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.

    • $limit stage to limit the output to 10 results.

    • $project stage to exclude all fields except title and add a field named score.

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Projections.*
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7
    8fun main() {
    9 // establish connection and set namespace
    10 val uri = "<connection-string>"
    11 val mongoClient = MongoClient.create(uri)
    12 val database = mongoClient.getDatabase("sample_mflix")
    13 val collection = database.getCollection<Document>("movies")
    14
    15 runBlocking {
    16 // define query
    17 val agg = Document(
    18 "\$search",
    19 Document("index", "synonyms-tutorial")
    20 .append(
    21 "text",
    22 Document("query", "automobile")
    23 .append("path", "title")
    24 .append("synonyms", "transportSynonyms")
    25 )
    26 )
    27
    28 // run query and print results
    29 val resultsFlow = collection.aggregate<Document>(
    30 listOf(
    31 agg,
    32 limit(10),
    33 project(fields(
    34 excludeId(),
    35 include("title"),
    36 computed("score", Document("\$meta", "searchScore"))
    37 ))
    38 )
    39 )
    40 resultsFlow.collect { println(it) }
    41 }
    42 mongoClient.close()
    43}
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Run the SynonymsEquivalentQuery.kt file.

    When you run the SynonymsEquivalentQuery.kt program in your IDE, it prints the following documents:

    Document{{title=Cars, score=4.140600204467773}}
    Document{{title=Planes, Trains & Automobiles, score=3.8122920989990234}}
    Document{{title=Blue Car, score=3.348478317260742}}
    Document{{title=Used Cars, score=3.348478317260742}}
    Document{{title=Cars 2, score=3.348478317260742}}
    Document{{title=Stealing Cars, score=3.348478317260742}}
    Document{{title=Cop Car, score=3.348478317260742}}
    Document{{title=Car Wash, score=3.348478317260742}}
    Document{{title=The Cars That Eat People, score=2.810762405395508}}
    Document{{title=Revenge of the Electric Car, score=2.810762405395508}}

    The Atlas 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. Atlas 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. Create a file named SynonymsExplicitQuery.kt.

  2. Copy and paste the following code into the file.

    The code example contains the following stages:

    • $search stage to search the title field for the word boat and uses the synonym mapping definition named transportSynonyms to search for words configured as synonyms of the query word boat in the synonyms source collection named transport_synonyms.

    • $limit stage to limit the output to 10 results.

    • $project stage to exclude all fields except title and add a field named score.

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Projections.*
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7
    8fun main() {
    9 // establish connection and set namespace
    10 val uri = "<connection-string>"
    11 val mongoClient = MongoClient.create(uri)
    12 val database = mongoClient.getDatabase("sample_mflix")
    13 val collection = database.getCollection<Document>("movies")
    14
    15 runBlocking {
    16 // define query
    17 val agg = Document(
    18 "\$search",
    19 Document("index", "synonyms-tutorial")
    20 .append(
    21 "text",
    22 Document("query", "boat")
    23 .append("path", "title")
    24 .append("synonyms", "transportSynonyms")
    25 )
    26 )
    27
    28 // run query and print results
    29 val resultsFlow = collection.aggregate<Document>(
    30 listOf(
    31 agg,
    32 limit(10),
    33 project(fields(
    34 excludeId(),
    35 include("title"),
    36 computed("score", Document("\$meta", "searchScore"))
    37 ))
    38 )
    39 )
    40 resultsFlow.collect { println(it) }
    41 }
    42 mongoClient.close()
    43}
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Run the SynonymsExplicitQuery.kt file.

    When you run the SynonymsExplicitQuery.kt program in your IDE, it prints the following documents:

    Document{{title=Vessel, score=5.3159894943237305}}
    Document{{title=Boats, score=4.597315311431885}}
    Document{{title=Sailing to Paradise, score=4.299008369445801}}
    Document{{title=And the Ship Sails On, score=4.299008369445801}}
    Document{{title=Broken Vessels, score=4.299008369445801}}
    Document{{title=Boat Trip, score=3.717820644378662}}
    Document{{title=Boat People, score=3.717820644378662}}
    Document{{title=Jack Goes Boating, score=3.1207938194274902}}
    Document{{title=The Glass Bottom Boat, score=3.1207938194274902}}
    Document{{title=Raspberry Boat Refugee, score=3.1207938194274902}}

    The Atlas Search results contain movies with boat, vessel, and sail in the title field because we configured boat, vessel, and sail to be synonyms of boat in the synonyms source collection named sample_synonyms, which is specified in the index for the collection.

    Atlas Search returns the following documents only for a search of the word vessel in the results:

    { "title" : "Vessel", "score" : 5.373150825500488 }
    { "title" : "Broken Vessels", "score" : 4.3452959060668945 }

    Atlas Search doesn't include documents with either boat or sail in the title field in the results because we didn't configure vessel to be a synonym of either boat or sail in the synonyms source collection. To test this, replace the value of the query field in the query above with vessel and run the query again.

    Similarly, Atlas Search returns the following documents only in the results for a search of the term sail:

    { "title" : "And the Ship Sails On", "score" : 4.3452959060668945 }
    { "title" : "Sailing to Paradise", "score" : 4.3452959060668945 }

    Atlas Search doesn't include documents with either boat or vessel in the title field in the results because we didn't configure sail to be a synonym of either boat or vessel in the synonyms source collection. To test this example, replace the value of the query field in the query above with sail and run the query again.

3

These code examples perform the following tasks:

  • Imports mongodb packages and dependencies.

  • Establishes a connection to your Atlas cluster.

  • Prints the documents that match the query from the AggregateFlow instance.

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

  1. Create a file named SynonymsEquivalentQuery.kt.

  2. Copy and paste the following code into the file.

    The code example contains the following stages:

    • $search stage to search 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.

    • $limit stage to limit the output to 10 results.

    • $project stage to exclude all fields except title and add a field named score.

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Projections.*
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7
    8fun main() {
    9 // establish connection and set namespace
    10 val uri = "<connection-string>"
    11 val mongoClient = MongoClient.create(uri)
    12 val database = mongoClient.getDatabase("sample_mflix")
    13 val collection = database.getCollection<Document>("movies")
    14
    15 runBlocking {
    16 // define query
    17 val agg = Document(
    18 "\$search",
    19 Document("index", "synonyms-tutorial")
    20 .append(
    21 "compound",
    22 Document(
    23 "should", listOf(
    24 Document(
    25 "text",
    26 Document("path", "title")
    27 .append("query", "automobile")
    28 .append("synonyms", "transportSynonyms")
    29 ),
    30 Document(
    31 "text",
    32 Document("path", "title")
    33 .append("query", "attire")
    34 .append("synonyms", "attireSynonyms")
    35 )
    36 )
    37 )
    38 )
    39 )
    40
    41 // run query and print results
    42 val resultsFlow = collection.aggregate<Document>(
    43 listOf(
    44 agg,
    45 limit(10),
    46 project(fields(
    47 excludeId(),
    48 include("title"),
    49 computed("score", Document("\$meta", "searchScore"))
    50 ))
    51 )
    52 )
    53 resultsFlow.collect { println(it) }
    54 }
    55 mongoClient.close()
    56}
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Run the SynonymsEquivalentQuery.kt file.

    When you run the SynonymsEquivalentQuery.kt program in your IDE, it prints the following documents:

    Document{{title=The Dress, score=4.852960586547852}}
    Document{{title=Cars, score=4.140600204467773}}
    Document{{title=27 Dresses, score=3.9245595932006836}}
    Document{{title=Planes, Trains & Automobiles, score=3.8122920989990234}}
    Document{{title=Car Wash, score=3.348478317260742}}
    Document{{title=Used Cars, score=3.348478317260742}}
    Document{{title=Blue Car, score=3.348478317260742}}
    Document{{title=Cars 2, score=3.348478317260742}}
    Document{{title=Stealing Cars, score=3.348478317260742}}
    Document{{title=Cop Car, score=3.348478317260742}}

    The Atlas 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.

    Atlas 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.

  1. Create a file named SynonymsExplicitQuery.kt.

  2. Copy and paste the following code into the file.

    The code example contains the following stages:

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

    • $limit stage to limit the output to 10 results.

    • $project stage to exclude all fields except title and add a field named score.

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Projections.*
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7
    8fun main() {
    9 // establish connection and set namespace
    10 val uri = "<connection-string>"
    11 val mongoClient = MongoClient.create(uri)
    12 val database = mongoClient.getDatabase("sample_mflix")
    13 val collection = database.getCollection<Document>("movies")
    14
    15 runBlocking {
    16 // define query
    17 val agg = Document(
    18 "\$search",
    19 Document("index", "synonyms-tutorial")
    20 .append(
    21 "compound",
    22 Document(
    23 "should", listOf(
    24 Document(
    25 "text",
    26 Document("path", "title")
    27 .append("query", "boat")
    28 .append("synonyms", "transportSynonyms")
    29 ),
    30 Document(
    31 "text",
    32 Document("path", "title")
    33 .append("query", "hat")
    34 .append("synonyms", "attireSynonyms")
    35 )
    36 )
    37 )
    38 )
    39 )
    40
    41 // run query and print results
    42 val resultsFlow = collection.aggregate<Document>(
    43 listOf(
    44 agg,
    45 limit(10),
    46 project(fields(
    47 excludeId(),
    48 include("title"),
    49 computed("score", Document("\$meta", "searchScore"))
    50 ))
    51 )
    52 )
    53
    54 resultsFlow.collect { println(it) }
    55 }
    56
    57 mongoClient.close()
    58}
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Run the SynonymsExplicitQuery.kt file.

    When you run the SynonymsExplicitQuery.kt program in your IDE, it prints the following documents:

    Document{{title=Fedora, score=5.6159772872924805}}
    Document{{title=Vessel, score=5.3159894943237305}}
    Document{{title=Boats, score=4.597315311431885}}
    Document{{title=And the Ship Sails On, score=4.299008369445801}}
    Document{{title=Broken Vessels, score=4.299008369445801}}
    Document{{title=Sailing to Paradise, score=4.299008369445801}}
    Document{{title=Top Hat, score=4.01986026763916}}
    Document{{title=A Hatful of Rain, score=4.01986026763916}}
    Document{{title=Boat People, score=3.717820644378662}}
    Document{{title=Boat Trip, score=3.717820644378662}}

    The Atlas Search results contain documents for both the search terms. The results contain movies with vessel, boat, and sail in the title field for the query term boat because we configured boat to be a synonym of boat, vessel, and sail in the synonyms source collection named transport_synonyms.

    Atlas Search doesn't include documents with either boat or sail in the title field in the results for a search of the term vessel because we didn't configure vessel to be a synonym of either boat or sail in the synonyms source collection. Similary, Atlas Search doesn't include documents with either boat or vessel in the title field in the results for a search of the term sail because we didn't configure sail to be a synonym of either boat or vessel in the synonyms source collection. To test these examples, replace the value of the query field in the query above with vessel or sail and run the query again.

    The result also contains movies with fedora and hat in the title field for the query term hat because we configured hat to be a synonym of hat, fedora, and headgear in the synonyms source collection named attire_synonyms.

    Atlas Search doesn't include documents with either hat or fedora in the title field in the results for a search of the term headgear because we didn't configure headgear to be a synonym of either hat or fedora in the synonyms source collection. Similary, Atlas Search doesn't include documents with either hat or headgear in the title field in the results for a search of the term fedora because we didn't configure fedora to be a synonym of either hat or headgear in the synonyms source collection. To test these examples, replace the value of the query field in the query above with fedora or headgear and run the query again.

1

These code examples perform the following tasks:

  • Imports mongodb, MongoDB's Node.js driver.

  • Creates an instance of the MongoClient class to establish a connection to your Atlas cluster.

  • Iterates over the cursor to print the documents that match the query.

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

  1. Create a file named synonyms-equivalent-query.js.

  2. Copy and paste the code example into the synonyms-equivalent-query.js file.

    The code example contains the following stages:

    • $search stage to search 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.

    • $limit stage to limit the output to 10 results.

    • $project stage to exclude all fields except title and add a field named score.

    1const MongoClient = require("mongodb").MongoClient;
    2const assert = require("assert");
    3
    4const agg = [
    5 {
    6 $search: {
    7 index: "synonyms-tutorial",
    8 text: {
    9 path: "title",
    10 query: "automobile",
    11 synonyms: "transportSynonyms",
    12 },
    13 },
    14 },
    15 {
    16 $limit: 10,
    17 },
    18 {
    19 $project: {
    20 _id: 0,
    21 title: 1,
    22 score: { $meta: "searchScore" },
    23 },
    24 },
    25];
    26
    27MongoClient.connect(
    28 "<connection-string>",
    29 { useNewUrlParser: true, useUnifiedTopology: true },
    30 async function (connectErr, client) {
    31 assert.equal(null, connectErr);
    32 const coll = client.db("sample_mflix").collection("movies");
    33 let cursor = await coll.aggregate(agg);
    34 await cursor.forEach((doc) => console.log(doc));
    35 client.close();
    36 }
    37);
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials.

  4. Run the following command to query your collection:

    node synonyms-equivalent-query.js
    { 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 Atlas 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. Atlas 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. Create a file named synonyms-explicit-query.js.

  2. Copy and paste the code example into the synonyms-explicit-query.js file.

    The code example contains the following stages:

    • $search stage to search the title field for the word boat and uses the synonym mapping definition named transportSynonyms to search for words configured as synonyms of the query word boat in the synonyms source collection named transport_synonyms.

    • $limit stage to limit the output to 10 results.

    • $project stage to exclude all fields except title and add a field named score.

    1const MongoClient = require("mongodb").MongoClient;
    2const assert = require("assert");
    3
    4const agg = [
    5 {
    6 $search: {
    7 index: "synonyms-tutorial",
    8 text: {
    9 path: "title",
    10 query: "boat",
    11 synonyms: "transportSynonyms",
    12 },
    13 },
    14 },
    15 {
    16 $limit: 10,
    17 },
    18 {
    19 $project: {
    20 _id: 0,
    21 title: 1,
    22 score: { $meta: "searchScore" },
    23 },
    24 },
    25];
    26
    27MongoClient.connect(
    28 "<connection-string>",
    29 { useNewUrlParser: true, useUnifiedTopology: true },
    30 async function (connectErr, client) {
    31 assert.equal(null, connectErr);
    32 const coll = client.db("sample_mflix").collection("movies");
    33 let cursor = await coll.aggregate(agg);
    34 await cursor.forEach((doc) => console.log(doc));
    35 client.close();
    36 }
    37);
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials.

  4. Run the following command to query your collection:

    node synonyms-explicit-query.js
    { title: 'Vessel', score: 5.373150825500488 }
    { title: 'Boats', score: 4.589139938354492 }
    { title: 'And the Ship Sails On', score: 4.3452959060668945 }
    { title: 'Broken Vessels', score: 4.3452959060668945 }
    { title: 'Sailing to Paradise', score: 4.3452959060668945 }
    { title: 'Boat People', score: 3.711261749267578 }
    { title: 'Boat Trip', score: 3.711261749267578 }
    { title: 'Three Men in a Boat', score: 3.1153182983398438 }
    { title: 'The Glass Bottom Boat', score: 3.1153182983398438 }
    { title: 'Jack Goes Boating', score: 3.1153182983398438 }

    The Atlas Search results contain movies with boat, vessel, and sail in the title field because we configured boat, vessel, and sail to be synonyms of boat in the synonyms source collection named sample_synonyms, which is specified in the index for the collection.

    Atlas Search returns the following documents only for a search of the word vessel in the results:

    { "title" : "Vessel", "score" : 5.373150825500488 }
    { "title" : "Broken Vessels", "score" : 4.3452959060668945 }

    Atlas Search doesn't include documents with either boat or sail in the title field in the results because we didn't configure vessel to be a synonym of either boat or sail in the synonyms source collection. To test this, replace the value of the query field in the query above with vessel and run the query again.

    Similarly, Atlas Search returns the following documents only in the results for a search of the term sail:

    { "title" : "And the Ship Sails On", "score" : 4.3452959060668945 }
    { "title" : "Sailing to Paradise", "score" : 4.3452959060668945 }

    Atlas Search doesn't include documents with either boat or vessel in the title field in the results because we didn't configure sail to be a synonym of either boat or vessel in the synonyms source collection. To test this example, replace the value of the query field in the query above with sail and run the query again.

2

These code examples perform the following tasks:

  • Imports mongodb, MongoDB's Node.js driver.

  • Creates an instance of the MongoClient class to establish a connection to your Atlas cluster.

  • Iterates over the cursor to print the documents that match the query.

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

  1. Create a file named synonyms-equivalent-query.js.

  2. Copy and paste the code example into the synonyms-equivalent-query.js file.

    The code example contains the following stages:

    • $search stage to search 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.

    • $limit stage to limit the output to 10 results.

    • $project stage to exclude all fields except title and add a field named score.

    1pconst MongoClient = require("mongodb").MongoClient;
    2const assert = require("assert");
    3
    4const agg = [
    5 {
    6 '$search': {
    7 'index': 'synonyms-tutorial',
    8 'compound': {
    9 'should': [
    10 {
    11 'text': {
    12 'path': 'title',
    13 'query': 'automobile',
    14 'synonyms': 'transportSynonyms'
    15 }
    16 }, {
    17 'text': {
    18 'path': 'title',
    19 'query': 'attire',
    20 'synonyms': 'attireSynonyms'
    21 }
    22 }
    23 ]
    24 }
    25 }
    26 }, {
    27 '$limit': 10
    28 }, {
    29 '$project': {
    30 '_id': 0,
    31 'title': 1,
    32 'score': {
    33 '$meta': 'searchScore'
    34 }
    35 }
    36 }
    37];
    38
    39MongoClient.connect(
    40 "<connection-string>",
    41 { useNewUrlParser: true, useUnifiedTopology: true },
    42 async function (connectErr, client) {
    43 assert.equal(null, connectErr);
    44 const coll = client.db("sample_mflix").collection("movies");
    45 let cursor = await coll.aggregate(agg);
    46 await cursor.forEach((doc) => console.log(doc));
    47 client.close();
    48 }
    49);
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials.

  4. Run the following command to query your collection:

    node synonyms-equivalent-query.js
    { 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 Atlas 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.

    Atlas 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.

  1. Create a file named synonyms-explicit-query.js.

  2. Copy and paste the code example into the synonyms-explicit-query.js file.

    The code example contains the following stages:

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

    • $limit stage to limit the output to 10 results.

    • $project stage to exclude all fields except title and add a field named score.

    1const MongoClient = require("mongodb").MongoClient;
    2const assert = require("assert");
    3
    4const agg = [
    5 {
    6 '$search': {
    7 'index': 'synonyms-tutorial',
    8 'compound': {
    9 'should': [
    10 {
    11 'text': {
    12 'path': 'title',
    13 'query': 'boat',
    14 'synonyms': 'transportSynonyms'
    15 }
    16 }, {
    17 'text': {
    18 'path': 'title',
    19 'query': 'hat',
    20 'synonyms': 'attireSynonyms'
    21 }
    22 }
    23 ]
    24 }
    25 }
    26 }, {
    27 '$limit': 10
    28 }, {
    29 '$project': {
    30 '_id': 0,
    31 'title': 1,
    32 'score': {
    33 '$meta': 'searchScore'
    34 }
    35 }
    36 }
    37];
    38
    39MongoClient.connect(
    40 "<connection-string>",
    41 { useNewUrlParser: true, useUnifiedTopology: true },
    42 async function (connectErr, client) {
    43 assert.equal(null, connectErr);
    44 const coll = client.db("sample_mflix").collection("movies");
    45 let cursor = await coll.aggregate(agg);
    46 await cursor.forEach((doc) => console.log(doc));
    47 client.close();
    48 }
    49);
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials.

  4. Run the following command to query your collection:

    node synonyms-explicit-query.js
    { title: 'Fedora', score: 5.673145294189453 }
    { title: 'Vessel', score: 5.373150825500488 }
    { title: 'Boats', score: 4.589139938354492 }
    { title: 'And the Ship Sails On', score: 4.3452959060668945 }
    { title: 'Broken Vessels', score: 4.3452959060668945 }
    { title: 'Sailing to Paradise', score: 4.3452959060668945 }
    { title: 'Top Hat', score: 4.066137313842773 }
    { title: 'A Hatful of Rain', score: 4.066137313842773 }
    { title: 'Boat People', score: 3.711261749267578 }
    { title: 'Boat Trip', score: 3.711261749267578 }

    The Atlas Search results contain documents for both the search terms. The results contain movies with vessel, boat, and sail in the title field for the query term boat because we configured boat to be a synonym of boat, vessel, and sail in the synonyms source collection named transport_synonyms.

    Atlas Search doesn't include documents with either boat or sail in the title field in the results for a search of the term vessel because we didn't configure vessel to be a synonym of either boat or sail in the synonyms source collection. Similary, Atlas Search doesn't include documents with either boat or vessel in the title field in the results for a search of the term sail because we didn't configure sail to be a synonym of either boat or vessel in the synonyms source collection. To test these examples, replace the value of the query field in the query above with vessel or sail and run the query again.

    The result also contains movies with fedora and hat in the title field for the query term hat because we configured hat to be a synonym of hat, fedora, and headgear in the synonyms source collection named attire_synonyms.

    Atlas Search doesn't include documents with either hat or fedora in the title field in the results for a search of the term headgear because we didn't configure headgear to be a synonym of either hat or fedora in the synonyms source collection. Similary, Atlas Search doesn't include documents with either hat or headgear in the title field in the results for a search of the term fedora because we didn't configure fedora to be a synonym of either hat or headgear in the synonyms source collection. To test these examples, replace the value of the query field in the query above with fedora or headgear and run the query again.

1

These code examples perform the following tasks:

  • Imports pymongo, MongoDB's Python driver, and the dns module, which is required to connect pymongo to Atlas using a DNS seed list connection string.

  • Creates an instance of the MongoClient class to establish a connection to your Atlas cluster.

  • Iterates over the cursor to print the documents that match the query.

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

  1. Create a file named synonyms-equivalent-query.py.

  2. Copy and paste the code example into the synonyms-equivalent.py file.

    The code example contains the following stages:

    • $search stage to search 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.

    • $limit stage to limit the output to 10 results

    • $project stage to exclude all fields except title and add a field named score

    1import pymongo
    2import dns
    3
    4client = pymongo.MongoClient('<connection-string>')
    5result = client['sample_mflix']['movies'].aggregate([
    6 {
    7 '$search': {
    8 'index': 'synonyms-tutorial',
    9 'text': {
    10 'path': 'title',
    11 'query': 'automobile',
    12 'synonyms': 'transportSynonyms'
    13 }
    14 }
    15 },
    16 {
    17 '$limit': 10
    18 },
    19 {
    20 '$project': {
    21 '_id': 0,
    22 'title': 1,
    23 'score': {
    24 '$meta': 'searchScore'
    25 }
    26 }
    27 }
    28])
    29
    30for i in result:
    31 print(i)
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials.

  4. Run the following command to query your collection:

    python synonyms-equivalent-query.py
    {'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 Atlas 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. Atlas 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. Create a file named synonyms-explicit-query.py.

  2. Copy and paste the code example into the synonyms-explicit.py file.

    The code example contains the following stages:

    • $search stage to search the title field for the word boat and uses the synonym mapping definition named transportSynonyms to search for words configured as synonyms of the query word boat in the synonyms source collection named transport_synonyms.

    • $limit stage to limit the output to 10 results.

    • $project stage to exclude all fields except title and add a field named score.

    1import pymongo
    2import dns
    3
    4client = pymongo.MongoClient('<connection-string>')
    5result = client['sample_mflix']['movies'].aggregate([
    6 {
    7 '$search': {
    8 'index': 'synonyms-tutorial',
    9 'text': {
    10 'path': 'title',
    11 'query': 'boat',
    12 'synonyms': 'transportSynonyms'
    13 }
    14 }
    15 },
    16 {
    17 '$limit': 10
    18 },
    19 {
    20 '$project': {
    21 '_id': 0,
    22 'title': 1,
    23 'score': {
    24 '$meta': 'searchScore'
    25 }
    26 }
    27 }
    28])
    29
    30for i in result:
    31 print(i)
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials.

  4. Run the following command to query your collection:

    python synonyms-explicit-query.py
    {'title': 'Vessel', 'score': 5.373150825500488}
    {'title': 'Boats', 'score': 4.589139938354492}
    {'title': 'And the Ship Sails On', 'score': 4.3452959060668945}
    {'title': 'Broken Vessels', 'score': 4.3452959060668945}
    {'title': 'Sailing to Paradise', 'score': 4.3452959060668945}
    {'title': 'Boat People', 'score': 3.711261749267578}
    {'title': 'Boat Trip', 'score': 3.711261749267578}
    {'title': 'Three Men in a Boat', 'score': 3.1153182983398438}
    {'title': 'The Glass Bottom Boat', 'score': 3.1153182983398438}
    {'title': 'Jack Goes Boating', 'score': 3.1153182983398438}

    The Atlas Search results contain movies with boat, vessel, and sail in the title field because we configured boat, vessel, and sail to be synonyms of boat in the synonyms source collection named sample_synonyms, which is specified in the index for the collection.

    Atlas Search returns the following documents only for a search of the word vessel in the results:

    { "title" : "Vessel", "score" : 5.373150825500488 }
    { "title" : "Broken Vessels", "score" : 4.3452959060668945 }

    Atlas Search doesn't include documents with either boat or sail in the title field in the results because we didn't configure vessel to be a synonym of either boat or sail in the synonyms source collection. To test this, replace the value of the query field in the query above with vessel and run the query again.

    Similarly, Atlas Search returns the following documents only in the results for a search of the term sail:

    { "title" : "And the Ship Sails On", "score" : 4.3452959060668945 }
    { "title" : "Sailing to Paradise", "score" : 4.3452959060668945 }

    Atlas Search doesn't include documents with either boat or vessel in the title field in the results because we didn't configure sail to be a synonym of either boat or vessel in the synonyms source collection. To test this example, replace the value of the query field in the query above with sail and run the query again.

2

These code examples perform the following tasks:

  • Imports pymongo, MongoDB's Python driver, and the dns module, which is required to connect pymongo to Atlas using a DNS seed list connection string.

  • Creates an instance of the MongoClient class to establish a connection to your Atlas cluster.

  • Iterates over the cursor to print the documents that match the query.

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

  1. Create a file named synonyms-equivalent-query.py.

  2. Copy and paste the code example into the synonyms-equivalent.py file.

    The code example contains the following stages:

    • $search stage to search 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.

    • $limit stage to limit the output to 10 results.

    • $project stage to exclude all fields except title and add a field named score.

    1import pymongo
    2import dns
    3
    4client = pymongo.MongoClient('<connection-string>')
    5result = client['sample_mflix']['movies'].aggregate([
    6 {
    7 '$search': {
    8 'index': 'synonyms-tutorial',
    9 'compound': {
    10 'should': [
    11 {
    12 'text': {
    13 'path': 'title',
    14 'query': 'automobile',
    15 'synonyms': 'transportSynonyms'
    16 }
    17 }, {
    18 'text': {
    19 'path': 'title',
    20 'query': 'attire',
    21 'synonyms': 'attireSynonyms'
    22 }
    23 }
    24 ]
    25 }
    26 }
    27 }, {
    28 '$limit': 10
    29 }, {
    30 '$project': {
    31 '_id': 0,
    32 'title': 1,
    33 'score': {
    34 '$meta': 'searchScore'
    35 }
    36 }
    37 }
    38])
    39
    40for i in result:
    41 print(i)
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials.

  4. Run the following command to query your collection:

    python synonyms-equivalent-query.py
    {'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 Atlas 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.

    Atlas 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.

  1. Create a file named synonyms-explicit-query.py.

  2. Copy and paste the code example into the synonyms-explicit.py file.

    The code example contains the following stages:

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

    • $limit stage to limit the output to 10 results.

    • $project stage to exclude all fields except title and add a field named score.

    1import pymongo
    2import dns
    3
    4client = pymongo.MongoClient('<connection-string>')
    5result = client['sample_mflix']['movies'].aggregate([
    6 {
    7 '$search': {
    8 'index': 'synonyms-tutorial',
    9 'compound': {
    10 'should': [
    11 {
    12 'text': {
    13 'path': 'title',
    14 'query': 'boat',
    15 'synonyms': 'transportSynonyms'
    16 }
    17 }, {
    18 'text': {
    19 'path': 'title',
    20 'query': 'hat',
    21 'synonyms': 'attireSynonyms'
    22 }
    23 }
    24 ]
    25 }
    26 }
    27 }, {
    28 '$limit': 10
    29 }, {
    30 '$project': {
    31 '_id': 0,
    32 'title': 1,
    33 'score': {
    34 '$meta': 'searchScore'
    35 }
    36 }
    37 }
    38])
    39
    40for i in result:
    41 print(i)
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials.

  4. Run the following command to query your collection:

    python synonyms-explicit-query.py
    {'title': 'Fedora', 'score': 5.673145294189453}
    {'title': 'Vessel', 'score': 5.373150825500488}
    {'title': 'Boats', 'score': 4.589139938354492}
    {'title': 'And the Ship Sails On', 'score': 4.3452959060668945}
    {'title': 'Broken Vessels', 'score': 4.3452959060668945}
    {'title': 'Sailing to Paradise', 'score': 4.3452959060668945}
    {'title': 'Top Hat', 'score': 4.066137313842773}
    {'title': 'A Hatful of Rain', 'score': 4.066137313842773}
    {'title': 'Boat People', 'score': 3.711261749267578}
    {'title': 'Boat Trip', 'score': 3.711261749267578}

    The Atlas Search results contain documents for both the search terms. The results contain movies with vessel, boat, and sail in the title field for the query term boat because we configured boat to be a synonym of boat, vessel, and sail in the synonyms source collection named transport_synonyms.

    Atlas Search doesn't include documents with either boat or sail in the title field in the results for a search of the term vessel because we didn't configure vessel to be a synonym of either boat or sail in the synonyms source collection. Similary, Atlas Search doesn't include documents with either boat or vessel in the title field in the results for a search of the term sail because we didn't configure sail to be a synonym of either boat or vessel in the synonyms source collection. To test these examples, replace the value of the query field in the query above with vessel or sail and run the query again.

    The result also contains movies with fedora and hat in the title field for the query term hat because we configured hat to be a synonym of hat, fedora, and headgear in the synonyms source collection named attire_synonyms.

    Atlas Search doesn't include documents with either hat or fedora in the title field in the results for a search of the term headgear because we didn't configure headgear to be a synonym of either hat or fedora in the synonyms source collection. Similary, Atlas Search doesn't include documents with either hat or headgear in the title field in the results for a search of the term fedora because we didn't configure fedora to be a synonym of either hat or headgear in the synonyms source collection. To test these examples, replace the value of the query field in the query above with fedora or headgear and run the query again.

Back

Facets