How to Use Synonyms with Atlas Search
On this page
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:
Load one or more sample synonyms source collections in the
sample_mflix
database.Create an Atlas Search index with one or more synonym mappings for the
sample_mflix.movies
collection.Run Atlas Search queries against the
title
field in thesample_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.
Load the Sample Synonyms Source Collection
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.
In Atlas, go to the Clusters page for your project.
If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it's not already displayed, select your desired project from the Projects menu in the navigation bar.
If it's not already displayed, click Clusters in the sidebar.
The Clusters page displays.
Go to the Collections page.
Click the Browse Collections button for your cluster.
The Data Explorer displays.
Create one or more sample synonyms collections in the sample_mflix
database.
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.
Expand the
sample_mflix
database and click the icon to open the Create Collection modal.Type
transport_synonyms
in the Collection name field.Click Create to create the collection in the
sample_mflix
database.
Expand the
sample_mflix
database and click the icon to open the Create Collection modal.Type
attire_synonyms
in the Collection name field.Click Create to create the collection in the
sample_mflix
database.
Load the sample data into the synonyms collection.
Follow the steps in the tabs to load data into the respective collection.
Select the
transport_synonyms
collection if it's not selected.Click Insert Document for each of the sample documents to add to the collection.
Click the JSON view ({}) to replace the default document.
Copy and paste the following sample documents, one at a time, and click Insert to add the documents, one at a time, to the collection.
{ "mappingType": "equivalent", "synonyms": ["car", "vehicle", "automobile"] } { "mappingType": "explicit", "input": ["boat"], "synonyms": ["boat", "vessel", "sail"] }
Select the
attire_synonyms
collection if it's not selected.Click Insert Document for each of the sample documents to add to the collection.
Click the JSON view ({}) to replace the default document.
Copy and paste the following sample documents, one at a time, and click Insert to add the documents, one at a time, to the collection.
{ "mappingType": "equivalent", "synonyms": ["dress", "apparel", "attire"] } { "mappingType": "explicit", "input": ["hat"], "synonyms": ["hat", "fedora", "headgear"] }
Create the Atlas Search Index With Synonym Mapping Definition
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.
In Atlas, go to the Clusters page for your project.
If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it's not already displayed, select your desired project from the Projects menu in the navigation bar.
If it's not already displayed, click Clusters in the sidebar.
The Clusters page displays.
Go to the Atlas Search page for your cluster.
You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.
In the sidebar, click Atlas Search under the Services heading.
From the Select data source dropdown, select your cluster and click Go to Atlas Search.
The Atlas Search page displays.
Click the Browse Collections button for your cluster.
Expand the database and select the collection.
Click the Search Indexes tab for the collection.
The Atlas Search page displays.
Click the cluster's name.
Click the Atlas Search tab.
The Atlas Search page displays.
Enter the Index Name, and set the Database and Collection.
In the Index Name field, enter
synonyms-tutorial
.If you name your index
default
, you don't need to specify anindex
parameter in the $search pipeline stage. If you give a custom name to your index, you must specify this name in theindex
parameter.In the Database and Collection section, find the
sample_mflix
database, and select themovies
collection.
Modify the default index definition.
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 thetitle
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 usingtransportSynonyms
mapping.transportSynonyms
can be used in text queries over any field indexed with thelucene.english
analyzer (including thetitle
field, in this example).
Click Next.
Click Refine Your Index.
Click Add Field in the Field Mappings section.
Click Customized Configuration.
Configure the following fields in the Add Field Mapping window and click Add after:
UI Field NameConfigurationField Name
Enter
title
.Enable Dynamic Mapping
Toggle to Off.
Data Type Configuration
Click Add Data Type.
Select String.
For Index Analyzer and Search Analyzer, click the dropdown to select lucene.english from the lucene.language analyzers dropdown.
For all other fields not listed above, accept the default.
Click Add Synonym Mapping in the Synonym Mappings section.
Configure the following fields in the Add Synonym Mapping window and click Add after:
UI Field NameConfigurationSynonym Mapping Name
Enter
transportSynonyms
.Synonym Source Collection
Select
transport_synonyms
.Analyzer
Select
lucene.english
.Click Save Changes.
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" } } ] } Click Next.
The following index definition specifies:
The language analyzer
lucene.standard
as the default analyzer for both indexing and querying thetitle
field.The name
transportSynonyms
andattireSynonyms
as the names for the synonym mappings.The
transport_synonyms
collection as the source synonyms collection to look for synonyms for queries usingtransportSynonyms
mapping.transportSynonyms
can be used in text queries over any field indexed with thelucene.standard
analyzer (including thetitle
field, in this sample query in this tutorial).The
attire_synonyms
collection as the source synonyms collection to look for synonyms for queries usingattireSynonyms
mapping.attireSynonyms
can be used in text queries over any field indexed with thelucene.standard
analyzer (including thetitle
field, in this example).
Click Next.
Click Refine Your Index.
Click Add Field in the Field Mappings section.
Configure the following fields in the Add Field Mapping window and then click Add:
UI Field NameConfigurationField Name
Enter
title
.Enable Dynamic Mapping
Toggle to Off.
Data Type Configuration
Select String.
For Index Analyzer and Search Analyzer, click the dropdown to select lucene.english from the lucene.language analyzers dropdown.
For all other fields not listed above, accept the default.
Click Add Synonym Mapping in the Synonym Mappings section.
Configure the following fields in the Add Synonym Mapping window and then click Add:
UI Field NameConfigurationSynonym Mapping Name
Enter
transportSynonyms
.Synonym Source Collection
Select
transport_synonyms
.Analyzer
Select
lucene.english
.Click Add Synonym Mapping again in the Synonym Mappings section.
Configure the following fields in the Add Synonym Mapping window and click Add after:
UI Field NameConfigurationSynonym Mapping Name
Enter
attireSynonyms
.Synonym Source Collection
Select
attire_synonyms
.Analyzer
Select
lucene.english
.Click Save Changes.
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" } } ] } Click Next.
Search the Collection
➤ 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.
In Atlas, go to the Clusters page for your project.
If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it's not already displayed, select your desired project from the Projects menu in the navigation bar.
If it's not already displayed, click Clusters in the sidebar.
The Clusters page displays.
Go to the Atlas Search page for your cluster.
You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.
In the sidebar, click Atlas Search under the Services heading.
From the Select data source dropdown, select your cluster and click Go to Atlas Search.
The Atlas Search page displays.
Click the Browse Collections button for your cluster.
Expand the database and select the collection.
Click the Search Indexes tab for the collection.
The Atlas Search page displays.
Click the cluster's name.
Click the Atlas Search tab.
The Atlas Search page displays.
Run the following example queries on the movies
collection.
If you created an index with a single synonym mapping definition, run the query from the following Simple Example 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.
Expand your query results.
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.
Connect to your cluster in mongosh
.
Open mongosh
in a terminal window and
connect to your cluster. For detailed instructions on connecting,
see Connect via mongosh
.
Use the sample_mflix
database.
Run the following command at mongosh
prompt:
use sample_mflix
Run the following example queries on the movies
collection.
If you created an index with a single synonym mapping definition, run the query in the Simple Example 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 to10
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.
Connect to your cluster in MongoDB Compass.
Open MongoDB Compass and connect to your cluster. For detailed instructions on connecting, see Connect via Compass.
Run simple Atlas Search queries on the movies
collection.
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 namedscore
To run this query in MongoDB Compass:
Click the Aggregations tab.
Click Select..., then configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click Add Stage to add additional stages.
Pipeline StageQuery$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
andautomobile
in thetitle
field although the query term isautomobile
because we configuredautomobile
to be a synonym ofcar
,vehicle
, andautomobile
in the synonyms source collection namedsample_synonyms
, which is specified in the index for the collection. Atlas Search returns the same results for a search of the wordscar
andvehicle
. To test this, replace the value of thequery
field in the query above with eithercar
orvehicle
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 namedscore
To run this query in MongoDB Compass:
Click the Aggregations tab.
Click Select..., then configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click Add Stage to add additional stages.
Pipeline StageQuery$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
, andsail
in thetitle
field because we configuredboat
,vessel
, andsail
to be synonyms ofboat
in the synonyms source collection namedsample_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
orsail
in thetitle
field in the results because we didn't configurevessel
to be a synonym of eitherboat
orsail
in the synonyms source collection. To test this, replace the value of thequery
field in the query above withvessel
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
orvessel
in thetitle
field in the results because we didn't configuresail
to be a synonym of eitherboat
orvessel
in the synonyms source collection. To test this example, replace the value of thequery
field in the query above withsail
and run the query again.
Run advanced Atlas Search queries if you created the index that contains multiple synonym mappings.
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 namedscore
To run this query in MongoDB Compass:
Click the Aggregations tab.
Click Select..., then configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click Add Stage to add additional stages.
Pipeline StageQuery$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 thetitle
field for the query termautomobile
because we configuredautomobile
to be a synonym ofcar
,vehicle
, andautomobile
in the synonyms source collection namedtransport_synonyms
. The result also contains movies withdress
in the title field for the query termattire
because we configuredattire
to be a synonym ofdress
,apparel
, andattire
in the synonyms source collection namedattire_synonyms
.Atlas Search returns the same results for a search of
car
orvehicle
in thetransport_synonyms
source collection anddress
orapparel
in theattire_synonyms
source collection. To test this example, replace the value of thequery
field in the query above withcar
orvehicle
and replace the value of thequery
field in the query above withdress
orapparel
, 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 namedscore
To run this query in MongoDB Compass:
Click the Aggregations tab.
Click Select..., then configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click Add Stage to add additional stages.
Pipeline StageQuery$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
, andsail
in thetitle
field for the query termboat
because we configuredboat
to be a synonym ofboat
,vessel
, andsail
in the synonyms source collection namedtransport_synonyms
.Atlas Search doesn't include documents with either
boat
orsail
in thetitle
field in the results for a search of the termvessel
because we didn't configurevessel
to be a synonym of eitherboat
orsail
in the synonyms source collection. Similary, Atlas Search doesn't include documents with eitherboat
orvessel
in thetitle
field in the results for a search of the termsail
because we didn't configuresail
to be a synonym of eitherboat
orvessel
in the synonyms source collection. To test these examples, replace the value of thequery
field in the query above withvessel
orsail
and run the query again.The result also contains movies with
fedora
andhat
in the title field for the query termhat
because we configuredhat
to be a synonym ofhat
,fedora
, andheadgear
in the synonyms source collection namedattire_synonyms
.Atlas Search doesn't include documents with either
hat
orfedora
in thetitle
field in the results for a search of the termheadgear
because we didn't configureheadgear
to be a synonym of eitherhat
orfedora
in the synonyms source collection. Similary, Atlas Search doesn't include documents with eitherhat
orheadgear
in thetitle
field in the results for a search of the termfedora
because we didn't configurefedora
to be a synonym of eitherhat
orheadgear
in the synonyms source collection. To test these examples, replace the value of thequery
field in the query above withfedora
orheadgear
and run the query again.
Run simple Atlas Search queries on the movies
collection.
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.
Create a file named
synonyms-equivalent-query.go
.Copy and paste the code example into the
synonyms-equivalent-query.go
file.The code example contains the following stages:
$search
stage to search thetitle
field for the wordautomobile
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordautomobile
in the synonyms source collection namedtransport_synonyms
.$limit
stage to limit the output to 10 results.$project
stage to exclude all fields excepttitle
and add a field namedscore
.
1 package main 2 3 import ( 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 14 type MovieCollection struct { 15 title string `bson:"Title,omitempty"` 16 } 17 18 func 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 } 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.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
andautomobile
in thetitle
field although the query term isautomobile
because we configuredautomobile
to be a synonym ofcar
,vehicle
, andautomobile
in the synonyms source collection namedsample_synonyms
, which is specified in the index for the collection. Atlas Search returns the same results for a search of the wordscar
andvehicle
. To test this, replace the value of thequery
field in the query above with eithercar
orvehicle
and run the query.
Create a file named
synonyms-explicit-query.go
.Copy and paste the code example into the
synonyms-explicit-query.go
file.The code example contains the following stages:
$search
stage to search thetitle
field for the wordboat
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordboat
in the synonyms source collection namedtransport_synonyms
.$limit
stage to limit the output to 10 results.$project
stage to exclude all fields excepttitle
and add a field namedscore
.
1 package main 2 3 import ( 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 14 type MovieCollection struct { 15 title string `bson:"Title,omitempty"` 16 } 17 18 func 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 } 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.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
, andsail
in thetitle
field because we configuredboat
,vessel
, andsail
to be synonyms ofboat
in the synonyms source collection namedsample_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
orsail
in thetitle
field in the results because we didn't configurevessel
to be a synonym of eitherboat
orsail
in the synonyms source collection. To test this, replace the value of thequery
field in the query above withvessel
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
orvessel
in thetitle
field in the results because we didn't configuresail
to be a synonym of eitherboat
orvessel
in the synonyms source collection. To test this example, replace the value of thequery
field in the query above withsail
and run the query again.
Run advanced Atlas Search queries if you created the index that contains multiple synonym mappings.
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.
Create a file named
synonyms-equivalent-query.go
.Copy and paste the code example into the
synonyms-equivalent-query.go
file.The code example contains the following stages:
$search
stage to search thetitle
field for the wordautomobile
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordautomobile
in the synonyms source collection namedtransport_synonyms
. The query searches thetitle
field for the wordattire
also and uses the synonym mapping definition namedattireSynonyms
to search for words configured as synonyms of the query wordattire
in the synonyms source collection namedattire_synonyms
.$limit
stage to limit the output to 10 results.$project
stage to exclude all fields excepttitle
and add a field namedscore
.
1 package main 2 3 import ( 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 14 type MovieCollection struct { 15 title string `bson:"Title,omitempty"` 16 } 17 18 func 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 } 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.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 thetitle
field for the query termautomobile
because we configuredautomobile
to be a synonym ofcar
,vehicle
, andautomobile
in the synonyms source collection namedtransport_synonyms
. The result also contains movies withdress
in the title field for the query termattire
because we configuredattire
to be a synonym ofdress
,apparel
, andattire
in the synonyms source collection namedattire_synonyms
.Atlas Search returns the same results for a search of
car
orvehicle
in thetransport_synonyms
source collection anddress
orapparel
in theattire_synonyms
source collection. To test this example, replace the value of thequery
field in the query above withcar
orvehicle
and replace the value of thequery
field in the query above withdress
orapparel
, and run the query again.
Create a file named
synonyms-explicit-query.go
.Copy and paste the code example into the
synonyms-explicit-query.go
file.The code example contains the following stages:
$search
stage to search thetitle
field for the wordboat
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordboat
in the synonyms source collection namedtransport_synonyms
. The query searches thetitle
field for the wordhat
also and uses the synonym mapping definition namedattireSynonyms
to search for words configured as synonyms of the query wordhat
in the synonyms source collection namedattire_synonyms
.$limit
stage to limit the output to 10 results.$project
stage to exclude all fields excepttitle
and add a field namedscore
.
1 package main 2 3 import ( 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 14 type MovieCollection struct { 15 title string `bson:"Title,omitempty"` 16 } 17 18 func 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 } 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.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
, andsail
in thetitle
field for the query termboat
because we configuredboat
to be a synonym ofboat
,vessel
, andsail
in the synonyms source collection namedtransport_synonyms
.Atlas Search doesn't include documents with either
boat
orsail
in thetitle
field in the results for a search of the termvessel
because we didn't configurevessel
to be a synonym of eitherboat
orsail
in the synonyms source collection. Similary, Atlas Search doesn't include documents with eitherboat
orvessel
in thetitle
field in the results for a search of the termsail
because we didn't configuresail
to be a synonym of eitherboat
orvessel
in the synonyms source collection. To test these examples, replace the value of thequery
field in the query above withvessel
orsail
and run the query again.The result also contains movies with
fedora
andhat
in the title field for the query termhat
because we configuredhat
to be a synonym ofhat
,fedora
, andheadgear
in the synonyms source collection namedattire_synonyms
.Atlas Search doesn't include documents with either
hat
orfedora
in thetitle
field in the results for a search of the termheadgear
because we didn't configureheadgear
to be a synonym of eitherhat
orfedora
in the synonyms source collection. Similary, Atlas Search doesn't include documents with eitherhat
orheadgear
in thetitle
field in the results for a search of the termfedora
because we didn't configurefedora
to be a synonym of eitherhat
orheadgear
in the synonyms source collection. To test these examples, replace the value of thequery
field in the query above withfedora
orheadgear
and run the query again.
Run simple Atlas Search queries on the movies
collection.
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.
Create a file named
SynonymsEquivalentQuery.java
.Copy and paste the following code into the file.
The code example contains the following stages:
$search
stage to search thetitle
field for the wordautomobile
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordautomobile
in the synonyms source collection namedtransport_synonyms
.$limit
stage to limit the output to 10 results.$project
stage to exclude all fields excepttitle
and add a field namedscore
.
1 import java.util.Arrays; 2 import static com.mongodb.client.model.Filters.eq; 3 import static com.mongodb.client.model.Aggregates.limit; 4 import static com.mongodb.client.model.Aggregates.project; 5 import static com.mongodb.client.model.Projections.excludeId; 6 import static com.mongodb.client.model.Projections.fields; 7 import static com.mongodb.client.model.Projections.include; 8 import static com.mongodb.client.model.Projections.computed; 9 import com.mongodb.client.MongoClient; 10 import com.mongodb.client.MongoClients; 11 import com.mongodb.client.MongoCollection; 12 import com.mongodb.client.MongoDatabase; 13 import org.bson.Document; 14 15 public 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; 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.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
andautomobile
in thetitle
field although the query term isautomobile
because we configuredautomobile
to be a synonym ofcar
,vehicle
, andautomobile
in the synonyms source collection namedsample_synonyms
, which is specified in the index for the collection. Atlas Search returns the same results for a search of the wordscar
andvehicle
. To test this, replace the value of thequery
field in the query above with eithercar
orvehicle
and run the query.
Create a file named
SynonymsExplicitQuery.java
.Copy and paste the following code into the file.
The code example contains the following stages:
$search
stage to search thetitle
field for the wordboat
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordboat
in the synonyms source collection namedtransport_synonyms
.$limit
stage to limit the output to 10 results.$project
stage to exclude all fields excepttitle
and add a field namedscore
.
1 import java.util.Arrays; 2 import static com.mongodb.client.model.Filters.eq; 3 import static com.mongodb.client.model.Aggregates.limit; 4 import static com.mongodb.client.model.Aggregates.project; 5 import static com.mongodb.client.model.Projections.excludeId; 6 import static com.mongodb.client.model.Projections.fields; 7 import static com.mongodb.client.model.Projections.include; 8 import static com.mongodb.client.model.Projections.computed; 9 import com.mongodb.client.MongoClient; 10 import com.mongodb.client.MongoClients; 11 import com.mongodb.client.MongoCollection; 12 import com.mongodb.client.MongoDatabase; 13 import org.bson.Document; 14 15 public 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; 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.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
, andsail
in thetitle
field because we configuredboat
,vessel
, andsail
to be synonyms ofboat
in the synonyms source collection namedsample_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
orsail
in thetitle
field in the results because we didn't configurevessel
to be a synonym of eitherboat
orsail
in the synonyms source collection. To test this, replace the value of thequery
field in the query above withvessel
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
orvessel
in thetitle
field in the results because we didn't configuresail
to be a synonym of eitherboat
orvessel
in the synonyms source collection. To test this example, replace the value of thequery
field in the query above withsail
and run the query again.
Run advanced Atlas Search queries if you created the index with multiple synonym mappings.
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.
Create a file named
SynonymsEquivalentQuery.java
.Copy and paste the following code into the file.
The code example contains the following stages:
$search
stage to search thetitle
field for the wordautomobile
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordautomobile
in the synonyms source collection namedtransport_synonyms
. The query searches thetitle
field for the wordattire
also and uses the synonym mapping definition namedattireSynonyms
to search for words configured as synonyms of the query wordattire
in the synonyms source collection namedattire_synonyms
.$limit
stage to limit the output to 10 results.$project
stage to exclude all fields excepttitle
and add a field namedscore
.
1 import java.util.Arrays; 2 import static com.mongodb.client.model.Filters.eq; 3 import static com.mongodb.client.model.Aggregates.limit; 4 import static com.mongodb.client.model.Aggregates.project; 5 import static com.mongodb.client.model.Projections.computed; 6 import static com.mongodb.client.model.Projections.excludeId; 7 import static com.mongodb.client.model.Projections.fields; 8 import static com.mongodb.client.model.Projections.include; 9 import com.mongodb.client.MongoClient; 10 import com.mongodb.client.MongoClients; 11 import com.mongodb.client.MongoCollection; 12 import com.mongodb.client.MongoDatabase; 13 import org.bson.Document; 14 15 public 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; 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.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 thetitle
field for the query termautomobile
because we configuredautomobile
to be a synonym ofcar
,vehicle
, andautomobile
in the synonyms source collection namedtransport_synonyms
. The result also contains movies withdress
in the title field for the query termattire
because we configuredattire
to be a synonym ofdress
,apparel
, andattire
in the synonyms source collection namedattire_synonyms
.Atlas Search returns the same results for a search of
car
orvehicle
in thetransport_synonyms
source collection anddress
orapparel
in theattire_synonyms
source collection. To test this example, replace the value of thequery
field in the query above withcar
orvehicle
and replace the value of thequery
field in the query above withdress
orapparel
, and run the query again.
Create a file named
SynonymsExplicitQuery.java
.Copy and paste the following code into the file.
The code example contains the following stages:
$search
stage to search thetitle
field for the wordboat
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordboat
in the synonyms source collection namedtransport_synonyms
. The query searches thetitle
field for the wordhat
also and uses the synonym mapping definition namedattireSynonyms
to search for words configured as synonyms of the query wordhat
in the synonyms source collection namedattire_synonyms
.$limit
stage to limit the output to 10 results.$project
stage to exclude all fields excepttitle
and add a field namedscore
.
1 import java.util.Arrays; 2 import static com.mongodb.client.model.Filters.eq; 3 import static com.mongodb.client.model.Aggregates.limit; 4 import static com.mongodb.client.model.Aggregates.project; 5 import static com.mongodb.client.model.Projections.computed; 6 import static com.mongodb.client.model.Projections.excludeId; 7 import static com.mongodb.client.model.Projections.fields; 8 import static com.mongodb.client.model.Projections.include; 9 import com.mongodb.client.MongoClient; 10 import com.mongodb.client.MongoClients; 11 import com.mongodb.client.MongoCollection; 12 import com.mongodb.client.MongoDatabase; 13 import org.bson.Document; 14 15 public 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; 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.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
, andsail
in thetitle
field for the query termboat
because we configuredboat
to be a synonym ofboat
,vessel
, andsail
in the synonyms source collection namedtransport_synonyms
.Atlas Search doesn't include documents with either
boat
orsail
in thetitle
field in the results for a search of the termvessel
because we didn't configurevessel
to be a synonym of eitherboat
orsail
in the synonyms source collection. Similary, Atlas Search doesn't include documents with eitherboat
orvessel
in thetitle
field in the results for a search of the termsail
because we didn't configuresail
to be a synonym of eitherboat
orvessel
in the synonyms source collection. To test these examples, replace the value of thequery
field in the query above withvessel
orsail
and run the query again.The result also contains movies with
fedora
andhat
in the title field for the query termhat
because we configuredhat
to be a synonym ofhat
,fedora
, andheadgear
in the synonyms source collection namedattire_synonyms
.Atlas Search doesn't include documents with either
hat
orfedora
in thetitle
field in the results for a search of the termheadgear
because we didn't configureheadgear
to be a synonym of eitherhat
orfedora
in the synonyms source collection. Similary, Atlas Search doesn't include documents with eitherhat
orheadgear
in thetitle
field in the results for a search of the termfedora
because we didn't configurefedora
to be a synonym of eitherhat
orheadgear
in the synonyms source collection. To test these examples, replace the value of thequery
field in the query above withfedora
orheadgear
and run the query again.
Run simple Atlas Search queries on the movies
collection.
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.
Create a file named
SynonymsEquivalentQuery.kt
.Copy and paste the following code into the file.
The code example contains the following stages:
$search
stage to search thetitle
field for the wordautomobile
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordautomobile
in the synonyms source collection namedtransport_synonyms
.$limit
stage to limit the output to 10 results.$project
stage to exclude all fields excepttitle
and add a field namedscore
.
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun 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 } 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.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
andautomobile
in thetitle
field although the query term isautomobile
because we configuredautomobile
to be a synonym ofcar
,vehicle
, andautomobile
in the synonyms source collection namedsample_synonyms
, which is specified in the index for the collection. Atlas Search returns the same results for a search of the wordscar
andvehicle
. To test this, replace the value of thequery
field in the query above with eithercar
orvehicle
and run the query.
Create a file named
SynonymsExplicitQuery.kt
.Copy and paste the following code into the file.
The code example contains the following stages:
$search
stage to search thetitle
field for the wordboat
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordboat
in the synonyms source collection namedtransport_synonyms
.$limit
stage to limit the output to 10 results.$project
stage to exclude all fields excepttitle
and add a field namedscore
.
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun 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 } 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.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
, andsail
in thetitle
field because we configuredboat
,vessel
, andsail
to be synonyms ofboat
in the synonyms source collection namedsample_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
orsail
in thetitle
field in the results because we didn't configurevessel
to be a synonym of eitherboat
orsail
in the synonyms source collection. To test this, replace the value of thequery
field in the query above withvessel
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
orvessel
in thetitle
field in the results because we didn't configuresail
to be a synonym of eitherboat
orvessel
in the synonyms source collection. To test this example, replace the value of thequery
field in the query above withsail
and run the query again.
Run advanced Atlas Search queries if you created the index with multiple synonym mappings.
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.
Create a file named
SynonymsEquivalentQuery.kt
.Copy and paste the following code into the file.
The code example contains the following stages:
$search
stage to search thetitle
field for the wordautomobile
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordautomobile
in the synonyms source collection namedtransport_synonyms
. The query searches thetitle
field for the wordattire
also and uses the synonym mapping definition namedattireSynonyms
to search for words configured as synonyms of the query wordattire
in the synonyms source collection namedattire_synonyms
.$limit
stage to limit the output to 10 results.$project
stage to exclude all fields excepttitle
and add a field namedscore
.
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun 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 } 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.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 thetitle
field for the query termautomobile
because we configuredautomobile
to be a synonym ofcar
,vehicle
, andautomobile
in the synonyms source collection namedtransport_synonyms
. The result also contains movies withdress
in the title field for the query termattire
because we configuredattire
to be a synonym ofdress
,apparel
, andattire
in the synonyms source collection namedattire_synonyms
.Atlas Search returns the same results for a search of
car
orvehicle
in thetransport_synonyms
source collection anddress
orapparel
in theattire_synonyms
source collection. To test this example, replace the value of thequery
field in the query above withcar
orvehicle
and replace the value of thequery
field in the query above withdress
orapparel
, and run the query again.
Create a file named
SynonymsExplicitQuery.kt
.Copy and paste the following code into the file.
The code example contains the following stages:
$search
stage to search thetitle
field for the wordboat
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordboat
in the synonyms source collection namedtransport_synonyms
. The query searches thetitle
field for the wordhat
also and uses the synonym mapping definition namedattireSynonyms
to search for words configured as synonyms of the query wordhat
in the synonyms source collection namedattire_synonyms
.$limit
stage to limit the output to 10 results.$project
stage to exclude all fields excepttitle
and add a field namedscore
.
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun 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 } 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.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
, andsail
in thetitle
field for the query termboat
because we configuredboat
to be a synonym ofboat
,vessel
, andsail
in the synonyms source collection namedtransport_synonyms
.Atlas Search doesn't include documents with either
boat
orsail
in thetitle
field in the results for a search of the termvessel
because we didn't configurevessel
to be a synonym of eitherboat
orsail
in the synonyms source collection. Similary, Atlas Search doesn't include documents with eitherboat
orvessel
in thetitle
field in the results for a search of the termsail
because we didn't configuresail
to be a synonym of eitherboat
orvessel
in the synonyms source collection. To test these examples, replace the value of thequery
field in the query above withvessel
orsail
and run the query again.The result also contains movies with
fedora
andhat
in the title field for the query termhat
because we configuredhat
to be a synonym ofhat
,fedora
, andheadgear
in the synonyms source collection namedattire_synonyms
.Atlas Search doesn't include documents with either
hat
orfedora
in thetitle
field in the results for a search of the termheadgear
because we didn't configureheadgear
to be a synonym of eitherhat
orfedora
in the synonyms source collection. Similary, Atlas Search doesn't include documents with eitherhat
orheadgear
in thetitle
field in the results for a search of the termfedora
because we didn't configurefedora
to be a synonym of eitherhat
orheadgear
in the synonyms source collection. To test these examples, replace the value of thequery
field in the query above withfedora
orheadgear
and run the query again.
Run simple Atlas Search queries on the movies
collection.
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.
Create a file named
synonyms-equivalent-query.js
.Copy and paste the code example into the
synonyms-equivalent-query.js
file.The code example contains the following stages:
$search
stage to search thetitle
field for the wordautomobile
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordautomobile
in the synonyms source collection namedtransport_synonyms
.$limit
stage to limit the output to 10 results.$project
stage to exclude all fields excepttitle
and add a field namedscore
.
1 const MongoClient = require("mongodb").MongoClient; 2 const assert = require("assert"); 3 4 const 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 27 MongoClient.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 ); Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials.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
andautomobile
in thetitle
field although the query term isautomobile
because we configuredautomobile
to be a synonym ofcar
,vehicle
, andautomobile
in the synonyms source collection namedsample_synonyms
, which is specified in the index for the collection. Atlas Search returns the same results for a search of the wordscar
andvehicle
. To test this, replace the value of thequery
field in the query above with eithercar
orvehicle
and run the query.
Create a file named
synonyms-explicit-query.js
.Copy and paste the code example into the
synonyms-explicit-query.js
file.The code example contains the following stages:
$search
stage to search thetitle
field for the wordboat
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordboat
in the synonyms source collection namedtransport_synonyms
.$limit
stage to limit the output to 10 results.$project
stage to exclude all fields excepttitle
and add a field namedscore
.
1 const MongoClient = require("mongodb").MongoClient; 2 const assert = require("assert"); 3 4 const 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 27 MongoClient.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 ); Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials.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
, andsail
in thetitle
field because we configuredboat
,vessel
, andsail
to be synonyms ofboat
in the synonyms source collection namedsample_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
orsail
in thetitle
field in the results because we didn't configurevessel
to be a synonym of eitherboat
orsail
in the synonyms source collection. To test this, replace the value of thequery
field in the query above withvessel
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
orvessel
in thetitle
field in the results because we didn't configuresail
to be a synonym of eitherboat
orvessel
in the synonyms source collection. To test this example, replace the value of thequery
field in the query above withsail
and run the query again.
Run advanced Atlas Search queries if you created the index with multiple synonym mappings.
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.
Create a file named
synonyms-equivalent-query.js
.Copy and paste the code example into the
synonyms-equivalent-query.js
file.The code example contains the following stages:
$search
stage to search thetitle
field for the wordautomobile
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordautomobile
in the synonyms source collection namedtransport_synonyms
. The query searches thetitle
field for the wordattire
also and uses the synonym mapping definition namedattireSynonyms
to search for words configured as synonyms of the query wordattire
in the synonyms source collection namedattire_synonyms
.$limit
stage to limit the output to 10 results.$project
stage to exclude all fields excepttitle
and add a field namedscore
.
1 pconst MongoClient = require("mongodb").MongoClient; 2 const assert = require("assert"); 3 4 const 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 39 MongoClient.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 ); Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials.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 thetitle
field for the query termautomobile
because we configuredautomobile
to be a synonym ofcar
,vehicle
, andautomobile
in the synonyms source collection namedtransport_synonyms
. The result also contains movies withdress
in the title field for the query termattire
because we configuredattire
to be a synonym ofdress
,apparel
, andattire
in the synonyms source collection namedattire_synonyms
.Atlas Search returns the same results for a search of
car
orvehicle
in thetransport_synonyms
source collection anddress
orapparel
in theattire_synonyms
source collection. To test this example, replace the value of thequery
field in the query above withcar
orvehicle
and replace the value of thequery
field in the query above withdress
orapparel
, and run the query again.
Create a file named
synonyms-explicit-query.js
.Copy and paste the code example into the
synonyms-explicit-query.js
file.The code example contains the following stages:
$search
stage to search thetitle
field for the wordboat
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordboat
in the synonyms source collection namedtransport_synonyms
. The query searches thetitle
field for the wordhat
also and uses the synonym mapping definition namedattireSynonyms
to search for words configured as synonyms of the query wordhat
in the synonyms source collection namedattire_synonyms
.$limit
stage to limit the output to 10 results.$project
stage to exclude all fields excepttitle
and add a field namedscore
.
1 const MongoClient = require("mongodb").MongoClient; 2 const assert = require("assert"); 3 4 const 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 39 MongoClient.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 ); Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials.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
, andsail
in thetitle
field for the query termboat
because we configuredboat
to be a synonym ofboat
,vessel
, andsail
in the synonyms source collection namedtransport_synonyms
.Atlas Search doesn't include documents with either
boat
orsail
in thetitle
field in the results for a search of the termvessel
because we didn't configurevessel
to be a synonym of eitherboat
orsail
in the synonyms source collection. Similary, Atlas Search doesn't include documents with eitherboat
orvessel
in thetitle
field in the results for a search of the termsail
because we didn't configuresail
to be a synonym of eitherboat
orvessel
in the synonyms source collection. To test these examples, replace the value of thequery
field in the query above withvessel
orsail
and run the query again.The result also contains movies with
fedora
andhat
in the title field for the query termhat
because we configuredhat
to be a synonym ofhat
,fedora
, andheadgear
in the synonyms source collection namedattire_synonyms
.Atlas Search doesn't include documents with either
hat
orfedora
in thetitle
field in the results for a search of the termheadgear
because we didn't configureheadgear
to be a synonym of eitherhat
orfedora
in the synonyms source collection. Similary, Atlas Search doesn't include documents with eitherhat
orheadgear
in thetitle
field in the results for a search of the termfedora
because we didn't configurefedora
to be a synonym of eitherhat
orheadgear
in the synonyms source collection. To test these examples, replace the value of thequery
field in the query above withfedora
orheadgear
and run the query again.
Run simple Atlas Search queries on the movies
collection.
These code examples perform the following tasks:
Imports
pymongo
, MongoDB's Python driver, and thedns
module, which is required to connectpymongo
toAtlas
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.
Create a file named
synonyms-equivalent-query.py
.Copy and paste the code example into the
synonyms-equivalent.py
file.The code example contains the following stages:
$search
stage to search thetitle
field for the wordautomobile
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordautomobile
in the synonyms source collection namedtransport_synonyms
.$limit
stage to limit the output to 10 results$project
stage to exclude all fields excepttitle
and add a field namedscore
1 import pymongo 2 import dns 3 4 client = pymongo.MongoClient('<connection-string>') 5 result = 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 30 for i in result: 31 print(i) Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials.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
andautomobile
in thetitle
field although the query term isautomobile
because we configuredautomobile
to be a synonym ofcar
,vehicle
, andautomobile
in the synonyms source collection namedsample_synonyms
, which is specified in the index for the collection. Atlas Search returns the same results for a search of the wordscar
andvehicle
. To test this, replace the value of thequery
field in the query above with eithercar
orvehicle
and run the query.
Create a file named
synonyms-explicit-query.py
.Copy and paste the code example into the
synonyms-explicit.py
file.The code example contains the following stages:
$search
stage to search thetitle
field for the wordboat
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordboat
in the synonyms source collection namedtransport_synonyms
.$limit
stage to limit the output to 10 results.$project
stage to exclude all fields excepttitle
and add a field namedscore
.
1 import pymongo 2 import dns 3 4 client = pymongo.MongoClient('<connection-string>') 5 result = 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 30 for i in result: 31 print(i) Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials.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
, andsail
in thetitle
field because we configuredboat
,vessel
, andsail
to be synonyms ofboat
in the synonyms source collection namedsample_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
orsail
in thetitle
field in the results because we didn't configurevessel
to be a synonym of eitherboat
orsail
in the synonyms source collection. To test this, replace the value of thequery
field in the query above withvessel
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
orvessel
in thetitle
field in the results because we didn't configuresail
to be a synonym of eitherboat
orvessel
in the synonyms source collection. To test this example, replace the value of thequery
field in the query above withsail
and run the query again.
Run advanced Atlas Search queries if you created the index with multiple synonym mappings.
These code examples perform the following tasks:
Imports
pymongo
, MongoDB's Python driver, and thedns
module, which is required to connectpymongo
toAtlas
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.
Create a file named
synonyms-equivalent-query.py
.Copy and paste the code example into the
synonyms-equivalent.py
file.The code example contains the following stages:
$search
stage to search thetitle
field for the wordautomobile
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordautomobile
in the synonyms source collection namedtransport_synonyms
. The query searches thetitle
field for the wordattire
also and uses the synonym mapping definition namedattireSynonyms
to search for words configured as synonyms of the query wordattire
in the synonyms source collection namedattire_synonyms
.$limit
stage to limit the output to 10 results.$project
stage to exclude all fields excepttitle
and add a field namedscore
.
1 import pymongo 2 import dns 3 4 client = pymongo.MongoClient('<connection-string>') 5 result = 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 40 for i in result: 41 print(i) Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials.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 thetitle
field for the query termautomobile
because we configuredautomobile
to be a synonym ofcar
,vehicle
, andautomobile
in the synonyms source collection namedtransport_synonyms
. The result also contains movies withdress
in the title field for the query termattire
because we configuredattire
to be a synonym ofdress
,apparel
, andattire
in the synonyms source collection namedattire_synonyms
.Atlas Search returns the same results for a search of
car
orvehicle
in thetransport_synonyms
source collection anddress
orapparel
in theattire_synonyms
source collection. To test this example, replace the value of thequery
field in the query above withcar
orvehicle
and replace the value of thequery
field in the query above withdress
orapparel
, and run the query again.
Create a file named
synonyms-explicit-query.py
.Copy and paste the code example into the
synonyms-explicit.py
file.The code example contains the following stages:
$search
stage to search thetitle
field for the wordboat
and uses the synonym mapping definition namedtransportSynonyms
to search for words configured as synonyms of the query wordboat
in the synonyms source collection namedtransport_synonyms
. The query searches thetitle
field for the wordhat
also and uses the synonym mapping definition namedattireSynonyms
to search for words configured as synonyms of the query wordhat
in the synonyms source collection namedattire_synonyms
.$limit
stage to limit the output to 10 results.$project
stage to exclude all fields excepttitle
and add a field namedscore
.
1 import pymongo 2 import dns 3 4 client = pymongo.MongoClient('<connection-string>') 5 result = 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 40 for i in result: 41 print(i) Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials.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
, andsail
in thetitle
field for the query termboat
because we configuredboat
to be a synonym ofboat
,vessel
, andsail
in the synonyms source collection namedtransport_synonyms
.Atlas Search doesn't include documents with either
boat
orsail
in thetitle
field in the results for a search of the termvessel
because we didn't configurevessel
to be a synonym of eitherboat
orsail
in the synonyms source collection. Similary, Atlas Search doesn't include documents with eitherboat
orvessel
in thetitle
field in the results for a search of the termsail
because we didn't configuresail
to be a synonym of eitherboat
orvessel
in the synonyms source collection. To test these examples, replace the value of thequery
field in the query above withvessel
orsail
and run the query again.The result also contains movies with
fedora
andhat
in the title field for the query termhat
because we configuredhat
to be a synonym ofhat
,fedora
, andheadgear
in the synonyms source collection namedattire_synonyms
.Atlas Search doesn't include documents with either
hat
orfedora
in thetitle
field in the results for a search of the termheadgear
because we didn't configureheadgear
to be a synonym of eitherhat
orfedora
in the synonyms source collection. Similary, Atlas Search doesn't include documents with eitherhat
orheadgear
in thetitle
field in the results for a search of the termfedora
because we didn't configurefedora
to be a synonym of eitherhat
orheadgear
in the synonyms source collection. To test these examples, replace the value of thequery
field in the query above withfedora
orheadgear
and run the query again.