How to Use Autocomplete with Atlas Search
This tutorial describes how to create an Atlas Search index that enables
autocomplete queries. In the following examples, the index enables
autocomplete
operators to query the specified field values.
Both examples take you through the following steps:
Set up an Atlas Search index with autocomplete data type for the
sample_mflix.movies
collection.Run Atlas Search queries against the specified fields in the
sample_mflix.movies
collection for an inputted sequence of characters.
Before you begin, ensure that your Atlas cluster meets the requirements described in the Prerequisites.
To create an Atlas Search index, you must have Project Data Access Admin
or higher access to the project.
Define an Index with Autocomplete
You can use the Atlas Search autocomplete
type to index text values in
string fields for autocompletion. You can configure an autocomplete
type to satisfy a variety of use cases. To learn more about the
configuration options available for the autocomplete
type, such as
tokenization strategy and diacritic folding, see
Configure autocomplete
Field Properties. You can query fields
indexed as autocomplete
type only using the autocomplete
operator.
In this section, you will create an Atlas Search index that indexes the title
and
plot
fields for autocompletion using the edgeGram
tokenization strategy.
In Atlas, go to the Clusters page for your project.
If it is not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it is not already displayed, select your desired project from the Projects menu in the navigation bar.
If the Clusters page is not already displayed, click Database in the sidebar.
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.
Click the Browse Collections button for your cluster.
Expand the database and select the collection.
Click the Search Indexes tab for the collection.
Click the cluster's name.
Click the Atlas Search tab.
Enter the Index Name, and set the Database and Collection.
In the Index Name field, enter
autocomplete-tutorial
.Note
If you name your index
default
, you don't need to specify anindex
parameter when using the $search pipeline stage. Otherwise, you must specify the index name using theindex
parameter.In the Database and Collection section, find the
sample_mflix
database, and select themovies
collection.
Specify an index definition with the autocomplete
field type.
You can use the Atlas Search Visual Editor or the Atlas Search JSON Editor in the Atlas user interface to create the index.
Click Next.
Click Refine Your Index.
Click Add Field in the Field Mappings section.
Configure the following field for autocompletion:
UI Field NameConfigurationField NameEntertitle
.Data TypeSelectAutocomplete
.Review the following default settings:
UI Field NameConfigurationMax Grams15
Min Grams2
TokenizationedgeGramFold DiacriticstrueClick Add.
Repeat steps c through g for the
plot
field.Click Save Changes.
Replace the default definition with the following index definition.
{ "mappings": { "dynamic": false, "fields": { "title": { "type": "autocomplete", "tokenization": "edgeGram", "foldDiacritics": true, "minGrams": 2, "maxGrams": 15 }, "plot": { "type": "autocomplete", "tokenization": "edgeGram", "foldDiacritics": true, "minGrams": 2, "maxGrams": 15 } } } } Click Next.
Run an Autocomplete Query
➤ Use the Select your language drop-down menu to set the language of the example on this page.
The autocomplete operator performs a search
for a word or phrase that contains a sequence of characters from an
incomplete input string. The fields that you intend to query with the
autocomplete
operator must be indexed with the autocomplete data type in the collection's index
definition.
In this section, you will connect to your Atlas cluster and run the sample
queries against the title
field in the sample_mflix.movies
collection
using the autocomplete
operator. This sample query uses a sequence of
characters to find movie titles that include words that begin with the input
character string.
In Atlas, go to the Clusters page for your project.
If it is not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it is not already displayed, select your desired project from the Projects menu in the navigation bar.
If the Clusters page is not already displayed, click Database in the sidebar.
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.
Click the Browse Collections button for your cluster.
Expand the database and select the collection.
Click the Search Indexes tab for the collection.
Click the cluster's name.
Click the Atlas Search tab.
Run an Atlas Search query with the autocomplete
operator on the movies
collection.
Copy and paste the following query into the Query Editor, and then click the Search button in the Query Editor.
[ { $search: { index: "autocomplete-tutorial", autocomplete: { query: "ger", path: "title" } } } ]
SCORE: 6.085907459259033 _id: "573a1390f29313caabcd50e5" plot: "The cartoonist, Winsor McCay, brings the Dinosaurus back to life in th…" genre: Array runtime: 12 SCORE: 6.085907459259033 _id: "573a1393f29313caabcddae1" plot: "Edmund, a young boy who lives in war-devastated Germany after the Seco…" genres: Array runtime: 78 SCORE: 6.085907459259033 _id: "573a1397f29313caabce6b75" plot: "Germany in Autumn does not have a plot per se; it mixes documentary fo…" genres: Array runtime: 123 SCORE: 6.085907459259033 _id: "573a1397f29313caabce77b5" plot: "Germany 1939. Hans and Lene marry the day before the war breaks out, a…" genres: Array runtime: 123 SCORE: 6.085907459259033 _id: "573a13d4f29313caabd99fa2" plot: "A documentary on the German artist that includes glimpses at his studi…" genres: Array runtime: 97 SCORE: 6.046686172485352 _id: "573a1399f29313caabcedb50" plot: "The story of the Apache chief and his armed resistance to the US Gover…" genres: Array runtime: 115 SCORE: 5.8947296142578125 _id: "573a13a5f29313caabd15dae" num_mflix_comments: 1 genres: Array runtime: 83 SCORE: 5.826231956481934 _id: "573a139bf29313caabcf36bd" plot: "Geri sets up a chess game to play his greatest opponent - himself." genres: Array runtime: 4 SCORE: 5.772464752197266 _id: "573a13d2f29313caabd922de" plot: "The true story of an Argentine family who lived with Josef Mengele wit…" genres: Array runtime: 93 SCORE: 5.772464752197266 _id: "573a13b4f29313caabd41bb7" plot: "In 1928, Dr. Max Gerson, a German-Jewish researcher, stumbled upon a t…" genres: Array countries: Array
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.
In these results, the characters ger
appear at the beginning of a word in
all the titles. Atlas Search returns results that begin with the specified query
string because the title
field is indexed using the edgeGram
tokenization strategy. Atlas Search includes Gèraldine
and Rece do gèry
in
the results because we set foldDiacritics
to true
.
In this section, you will connect to your Atlas cluster and run the sample
queries against the title
and plot
fields in the
sample_mflix.movies
collection using the autocomplete
and compound
operators. This sample query uses a sequence of characters to find movie
titles and corresponding plots with words that begin with the same input
character string.
In Atlas, go to the Clusters page for your project.
If it is not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it is not already displayed, select your desired project from the Projects menu in the navigation bar.
If the Clusters page is not already displayed, click Database in the sidebar.
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.
Click the Browse Collections button for your cluster.
Expand the database and select the collection.
Click the Search Indexes tab for the collection.
Click the cluster's name.
Click the Atlas Search tab.
Run an Atlas Search query with the compound
and autocomplete
operators on the movies
collection.
Copy and paste the following query into the Query Editor, and then click the Search button in the Query Editor.
[ { $search: { index: "autocomplete-tutorial", compound: { should: [{ autocomplete: { query: "pri", path: "title" } }, { autocomplete: { query: "pri", path: "plot" } }], minimumShouldMatch: 1 } } } ]
SCORE: 7.52535343170166 _id: "573a13e7f29313caabdc80cd" plot: "Prison Terminal: The Last Days of Private Jack Hall is a moving cinema…" genre: Array runtime: 40 SCORE: 7.235145568847656 _id: "573a13adf29313caabd2b504" plot: "Now settled in Genovia, Princess Mia faces a new revelation: she is be…" genres: Array runtime: 113 SCORE: 7.202958106994629 _id: "573a13b5f29313caabd43816" plot: "A young fugitive prince and princess must stop a villain who unknowing…" genres: Array runtime: 116 SCORE: 7.201740264892578 _id: "573a139af29313caabcf0d54" plot: "The first wedding anniversary of Princess Odette and Prince Derek is d…" genres: Array runtime: 71 SCORE: 7.174992561340332 _id: "573a1399f29313caabceeead" plot: "Jane Austen's classic novel about the prejudice that occurred between …" genres: Array runtime: 327 SCORE: 7.173888206481934 _id: "573a13c1f29313caabd63a21" plot: "A princess whose country has been invaded goes into hiding in Louisian…" genres: Array countries: Array SCORE: 7.163987159729004 _id: "573a13eef29313caabdd51a6" plot: "Follows the people racing to bring the hot new 3D printing technology …" genres: Array runtime: 100 SCORE: 7.155245780944824 _id: "573a13a5f29313caabd14adf" plot: "When her father is captured by The Sheriff of Nottingham and Prince Jo…" genres: Array runtime: 88 SCORE: 7.146618843078613 _id: "573a139af29313caabcf0efc" plot: "An Egyptian prince learns of his identity as a Hebrew and, later his d…" genres: Array runtime: 99 SCORE: 7.132328987121582 _id: "573a139af29313caabcf003b" plot: "Two Russian soldiers, one battle-seasoned and the other barely into hi…" genres: Array runtime: 99
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.
In these results, the characters pri
appear at the beginning of a word in
all the titles and plots. Atlas Search returns results that begin with the specified
query string because the title
and plot
fields are indexed using the
edgeGram
tokenization strategy.
In this section, you will connect to your Atlas cluster and run the sample
queries against the title
field in the sample_mflix.movies
collection
using the autocomplete
operator. This sample query uses a sequence of
characters to find movie titles that include words that begin with the input
character string.
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 an Atlas Search query with the autocomplete
operator on the movies
collection.
The following query searches for movies with the characters ger
in
the title
field. The query includes the $limit
stage to limit
the output to 20 results and the $project
stage to exclude all
fields except title
.
db.movies.aggregate([ { $search: { "index": "autocomplete-tutorial", "autocomplete": { "path": "title", "query": "ger" } } }, { $limit: 20 }, { $project: { "_id": 0, "title": 1 } } ])
{ title: "Gertie the Dinosaur" }, { title: "Germany Year Zero" }, { title: "Germany in Autumn" }, { title: "Germany Pale Mother" }, { title: "Gerhard Richter - Painting" }, { title: "Geronimo: An American Legend" }, { title: "How to Live in the German Federal Republic" }, { title: "Geri's Game" }, { title: "The Gerson Miracle" }, { title: "The German Doctor" }, { title: "From Caligari to Hitler: German Cinema in the Age of the Masse"}, { title: "From Caligari to Hitler: German Cinema in the Age of the Masses"}, { title: "Gèraldine" }, { title: "Gervaise" }, { title: "Gertrud" }, { title: "Germinal" }, { title: "Gerry" }, { title: "Gerontophilia" }, { title: "Pionery-geroi" }, { title: "The Good German" }
In these results, the characters ger
appear at the beginning of a word in
all the titles. Atlas Search returns results that begin with the specified query
string because the title
field is indexed using the edgeGram
tokenization strategy. Atlas Search includes Gèraldine
and Rece do gèry
in
the results because we set foldDiacritics
to true
.
In this section, you will connect to your Atlas cluster and run the sample
queries against the title
and plot
fields in the
sample_mflix.movies
collection using the autocomplete
and compound
operators. This sample query uses a sequence of characters to find movie
titles and corresponding plots with words that begin with the same input
character string.
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 an Atlas Search query with the compound
and autocomplete
operators on the movies
collection.
The following query searches for movies with the characters pri
in
the title
and plot
field. The query includes the $limit
stage to limit the output to five results and the $project
stage
to exclude all fields except title
and plot
.
1 db.movies.aggregate([ 2 { 3 "$search": { 4 "index": "autocomplete-tutorial", 5 "compound": { 6 "should": [{ 7 "autocomplete": { 8 "query": "pri", 9 "path": "title" 10 } 11 }, 12 { 13 "autocomplete": { 14 "query": "pri", 15 "path": "plot" 16 } 17 }], 18 "minimumShouldMatch": 1 19 } 20 } 21 }, 22 { 23 "$limit": 5 24 }, 25 { 26 "$project": { 27 "_id": 0, 28 "title": 1, 29 "plot": 1 30 } 31 } 32 ])
{ plot: 'Prison Terminal: The Last Days of Private Jack Hall is a moving cinema verite documentary that breaks through the walls of one of Americas oldest maximum security prisons to tell the story ...', title: 'Prison Terminal: The Last Days of Private Jack Hall' } { plot: 'Now settled in Genovia, Princess Mia faces a new revelation: she is being primed for an arranged marriage to an English suitor.', title: 'The Princess Diaries 2: Royal Engagement' } { plot: 'A young fugitive prince and princess must stop a villain who unknowingly threatens to destroy the world with a special dagger that enables the magic sand inside to reverse time.', title: 'Prince of Persia: The Sands of Time' } { plot: 'The first wedding anniversary of Princess Odette and Prince Derek is distracted by field fires set by Knuckles. His master Clavius, wants to conquer the world, and he needs to capture a ...', title: 'The Swan Princess: Escape from Castle Mountain' } { plot: "Jane Austen's classic novel about the prejudice that occurred between the 19th century classes and the pride which would keep lovers apart.", title: 'Pride and Prejudice' }
In these results, the characters pri
appear at the beginning of a word in
all the titles and plots. Atlas Search returns results that begin with the specified
query string because the title
and plot
fields are indexed using the
edgeGram
tokenization strategy.
In this section, you will connect to your Atlas cluster and run the sample
queries against the title
field in the sample_mflix.movies
collection
using the autocomplete
operator. This sample query uses a sequence of
characters to find movie titles that include words that begin with the input
character string.
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 an Atlas Search query with the autocomplete
operator on the movies
collection.
The query uses the following pipeline stages:
$search
to search thetitle
field using theautocomplete
operator for words that begin with the charactersger
$limit stage to limit the output to 20 results
$project stage to exclude all fields except
title
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.
In the Aggregations tab of the
movies
collection, 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": "autocomplete-tutorial", "autocomplete": { "query": "ger", "path": "title" } } $limit
20 $project
{ "_id": 0, "title": 1, }
If you enabled Auto Preview, MongoDB Compass displays the
following documents next to the $autocomplete
pipeline stage:
1 { title: "Gertie the Dinosaur" }, 2 { title: "Germany Year Zero" }, 3 { title: "Germany in Autumn" }, 4 { title: "Germany Pale Mother" }, 5 { title: "Gerhard Richter - Painting" }, 6 { title: "Geronimo: An American Legend" }, 7 { title: "How to Live in the German Federal Republic" }, 8 { title: "Geri's Game" }, 9 { title: "The Gerson Miracle" }, 10 { title: "The German Doctor" }, 11 { title: "From Caligari to Hitler: German Cinema in the Age of the Masse"}, 12 { title: "From Caligari to Hitler: German Cinema in the Age of the Masses"}, 13 { title: "Gèraldine" }, 14 { title: "Gervaise" }, 15 { title: "Gertrud" }, 16 { title: "Germinal" }, 17 { title: "Gerry" }, 18 { title: "Gerontophilia" }, 19 { title: "Pionery-geroi" }, 20 { title: "The Good German" }
In these results, the characters ger
appear at the beginning of a word in
all the titles. Atlas Search returns results that begin with the specified query
string because the title
field is indexed using the edgeGram
tokenization strategy. Atlas Search includes Gèraldine
and Rece do gèry
in
the results because we set foldDiacritics
to true
.
In this section, you will connect to your Atlas cluster and run the sample
queries against the title
and plot
fields in the
sample_mflix.movies
collection using the autocomplete
and compound
operators. This sample query uses a sequence of characters to find movie
titles and corresponding plots with words that begin with the same input
character string.
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 an Atlas Search query with the autocomplete
operator on the movies
collection.
The query uses the following pipeline stages:
$search
to search thetitle
andplot
fields using theautocomplete
operator for words that begin with the characterspri
$limit stage to limit the output to 5 results
$project stage to exclude all fields except
title
andplot
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.
In the Aggregations tab of the
movies
collection, 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": "autocomplete-tutorial", "compound": { "should": [{ "autocomplete": { "query": "pri", "path": "title" } }, { "autocomplete": { "query": "pri", "path": "plot" } }], "minimumShouldMatch": 1 } } $limit
5 $project
{ "_id": 0, "title": 1, "plot": 1 }
If you enabled Auto Preview, MongoDB Compass displays the
following documents next to the $autocomplete
pipeline stage:
1 { 2 plot: 'Prison Terminal: The Last Days of Private Jack Hall is a moving cinema verite documentary that breaks through the walls of one of Americas oldest maximum security prisons to tell the story ...', 3 title: 'Prison Terminal: The Last Days of Private Jack Hall' 4 } 5 { 6 plot: 'Now settled in Genovia, Princess Mia faces a new revelation: she is being primed for an arranged marriage to an English suitor.', 7 title: 'The Princess Diaries 2: Royal Engagement' 8 } 9 { 10 plot: 'A young fugitive prince and princess must stop a villain who unknowingly threatens to destroy the world with a special dagger that enables the magic sand inside to reverse time.', 11 title: 'Prince of Persia: The Sands of Time' 12 } 13 { 14 plot: 'The first wedding anniversary of Princess Odette and Prince Derek is distracted by field fires set by Knuckles. His master Clavius, wants to conquer the world, and he needs to capture a ...', 15 title: 'The Swan Princess: Escape from Castle Mountain' 16 } 17 { 18 plot: "Jane Austen's classic novel about the prejudice that occurred between the 19th century classes and the pride which would keep lovers apart.", 19 title: 'Pride and Prejudice' 20 }
In these results, the characters pri
appear at the beginning of a word in
all the titles and plots. Atlas Search returns results that begin with the specified
query string because the title
and plot
fields are indexed using the
edgeGram
tokenization strategy.
In this section, you will connect to your Atlas cluster and run the sample
queries against the title
field in the sample_mflix.movies
collection
using the autocomplete
operator. This sample query uses a sequence of
characters to find movie titles that include words that begin with the input
character string.
Set up and initialize the .NET/C# project for the query.
Create a new directory called
basic-autocomplete-example
and initialize your project with thedotnet new
command.mkdir basic-autocomplete-example cd basic-autocomplete-example dotnet new console Add the .NET/C# Driver to your project as a dependency.
dotnet add package MongoDB.Driver
Create the query in the Program.cs
file.
Replace the contents of the
Program.cs
file with the following code.The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class AutocompleteBasicExample 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 // define and run pipeline 23 var results = moviesCollection.Aggregate() 24 .Search(Builders<MovieDocument>.Search.Autocomplete(movie => movie.Title, "ger"), indexName: "autocomplete-tutorial") 25 .Project<MovieDocument>(Builders<MovieDocument>.Projection 26 .Include(movie => movie.Title) 27 .Exclude(movie => movie.Id)) 28 .Limit(20) 29 .ToList(); 30 31 // print results 32 foreach (var movie in results) 33 { 34 Console.WriteLine(movie.ToJson()); 35 } 36 } 37 } 38 39 [ ]40 public class MovieDocument 41 { 42 [ ]43 public ObjectId Id { get; set; } 44 public string Title { get; set; } 45 } 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 the Program.cs
file.
dotnet run basic-autocomplete-example.csproj
{ "title" : "Gertie the Dinosaur" } { "title" : "Germany Year Zero" } { "title" : "Germany in Autumn" } { "title" : "Germany Pale Mother" } { "title" : "Gerhard Richter - Painting" } { "title" : "Geronimo: An American Legend" } { "title" : "How to Live in the German Federal Republic" } { "title" : "Geri's Game" } { "title" : "The Gerson Miracle" } { "title" : "The German Doctor" } { "title" : "From Caligari to Hitler: German Cinema in the Age of the Masses" } { "title" : "From Caligari to Hitler: German Cinema in the Age of the Masses" } { "title" : "Gèraldine" } { "title" : "Gervaise" } { "title" : "Gertrud" } { "title" : "Germinal" } { "title" : "Gerry" } { "title" : "Gerontophilia" } { "title" : "Pionery-geroi" } { "title" : "The Good German" }
In these results, the characters ger
appear at the beginning of a word in
all the titles. Atlas Search returns results that begin with the specified query
string because the title
field is indexed using the edgeGram
tokenization strategy. Atlas Search includes Gèraldine
and Rece do gèry
in
the results because we set foldDiacritics
to true
.
In this section, you will connect to your Atlas cluster and run the sample
queries against the title
and plot
fields in the
sample_mflix.movies
collection using the autocomplete
and compound
operators. This sample query uses a sequence of characters to find movie
titles and corresponding plots with words that begin with the same input
character string.
Set up and initialize the .NET/C# project for the query.
Create a new directory called
advanced-autocomplete-example
and initialize your project with thedotnet new
command.mkdir advanced-autocomplete-example cd advanced-autocomplete-example dotnet new console Add the .NET/C# Driver to your project as a dependency.
dotnet add package MongoDB.Driver
Create the query in the Program.cs
file.
Replace the contents of the
Program.cs
file with the following code.The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class AutocompleteAdvancedExample 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 // define and run pipeline 23 var results = moviesCollection.Aggregate() 24 .Search(Builders<MovieDocument>.Search.Compound() 25 .Should(Builders<MovieDocument>.Search.Autocomplete(movie => movie.Title, "pri")) 26 .Should(Builders<MovieDocument>.Search.Autocomplete(movie => movie.Plot, "pri")) 27 .MinimumShouldMatch(1), 28 indexName: "autocomplete-tutorial") 29 .Project<MovieDocument>(Builders<MovieDocument>.Projection 30 .Include(movie => movie.Plot) 31 .Include(movie => movie.Title) 32 .Exclude(movie => movie.Id)) 33 .Limit(5) 34 .ToList(); 35 36 // print results 37 foreach (var movie in results) 38 { 39 Console.WriteLine(movie.ToJson()); 40 } 41 } 42 } 43 44 [ ]45 public class MovieDocument 46 { 47 [ ]48 public ObjectId Id { get; set; } 49 public string Plot { get; set; } 50 public string Title { get; set; } 51 } 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 the Program.cs
file.
dotnet run advanced-autocomplete-example.csproj
{ "plot" : "Prison Terminal: The Last Days of Private Jack Hall is a moving cinema verite documentary that breaks through the walls of one of Americas oldest maximum security prisons to tell the story ...", "title" : "Prison Terminal: The Last Days of Private Jack Hall" } { "plot" : "Now settled in Genovia, Princess Mia faces a new revelation: she is being primed for an arranged marriage to an English suitor.", "title" : "The Princess Diaries 2: Royal Engagement" } { "plot" : "A young fugitive prince and princess must stop a villain who unknowingly threatens to destroy the world with a special dagger that enables the magic sand inside to reverse time.", "title" : "Prince of Persia: The Sands of Time" } { "plot" : "The first wedding anniversary of Princess Odette and Prince Derek is distracted by field fires set by Knuckles. His master Clavius, wants to conquer the world, and he needs to capture a ...", "title" : "The Swan Princess: Escape from Castle Mountain" } { "plot" : "Jane Austen's classic novel about the prejudice that occurred between the 19th century classes and the pride which would keep lovers apart.", "title" : "Pride and Prejudice" }
In these results, the characters pri
appear at the beginning of a word in
all the titles and plots. Atlas Search returns results that begin with the specified
query string because the title
and plot
fields are indexed using the
edgeGram
tokenization strategy.
In this section, you will connect to your Atlas cluster and run the sample
queries against the title
field in the sample_mflix.movies
collection
using the autocomplete
operator. This sample query uses a sequence of
characters to find movie titles that include words that begin with the input
character string.
Run an Atlas Search query with the autocomplete
operator on the movies
collection.
Create a file named
autocomplete-query.go
.Copy and paste the following code into the
autocomplete-query.go
file.The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 7 "go.mongodb.org/mongo-driver/bson" 8 "go.mongodb.org/mongo-driver/mongo" 9 "go.mongodb.org/mongo-driver/mongo/options" 10 ) 11 12 func main() { 13 // connect to your Atlas cluster 14 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>")) 15 if err != nil { 16 panic(err) 17 } 18 defer client.Disconnect(context.TODO()) 19 20 // set namespace 21 collection := client.Database("sample_mflix").Collection("movies") 22 23 // define pipeline stages 24 searchStage := bson.D{{"$search", bson.D{{"index", "autocomplete-tutorial"}, {"autocomplete", bson.D{{"query", "ger"}, {"path", "title"}}}}}} 25 limitStage := bson.D{{"$limit", 20}} 26 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}}}} 27 // run pipeline 28 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage}) 29 if err != nil { 30 panic(err) 31 } 32 33 // print results 34 var results []bson.D 35 if err = cursor.All(context.TODO(), &results); err != nil { 36 panic(err) 37 } 38 for _, result := range results { 39 fmt.Println(result) 40 } 41 } 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 autocomplete-query.go [{title Gertie the Dinosaur}] [{title Germany Year Zero}] [{title Germany in Autumn}] [{title Germany Pale Mother}] [{title Gerhard Richter - Painting}] [{title Geronimo: An American Legend}] [{title How to Live in the German Federal Republic}] [{title Geri's Game}] [{title The Gerson Miracle}] [{title The German Doctor}] [{title From Caligari to Hitler: German Cinema in the Age of the Masses}] [{title From Caligari to Hitler: German Cinema in the Age of the Masses}] [{title Gèraldine}] [{title Gervaise}] [{title Gertrud}] [{title Germinal}] [{title Gerry}] [{title Gerontophilia}] [{title Pionery-geroi}] [{title The Good German}]
In these results, the characters ger
appear at the beginning of a word in
all the titles. Atlas Search returns results that begin with the specified query
string because the title
field is indexed using the edgeGram
tokenization strategy. Atlas Search includes Gèraldine
and Rece do gèry
in
the results because we set foldDiacritics
to true
.
In this section, you will connect to your Atlas cluster and run the sample
queries against the title
and plot
fields in the
sample_mflix.movies
collection using the autocomplete
and compound
operators. This sample query uses a sequence of characters to find movie
titles and corresponding plots with words that begin with the same input
character string.
Run an Atlas Search query with the autocomplete
operator on the movies
collection.
Create a file named
autocomplete-query.go
.Copy and paste the following code into the
autocomplete-query.go
file.The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 7 "go.mongodb.org/mongo-driver/bson" 8 "go.mongodb.org/mongo-driver/mongo" 9 "go.mongodb.org/mongo-driver/mongo/options" 10 ) 11 12 func main() { 13 // connect to your Atlas cluster 14 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>")) 15 if err != nil { 16 panic(err) 17 } 18 defer client.Disconnect(context.TODO()) 19 20 // set namespace 21 collection := client.Database("sample_mflix").Collection("movies") 22 23 // define pipeline stages 24 searchStage := bson.D{ 25 {"$search", bson.D{ 26 {"index", "autocomplete-tutorial"}, 27 {"compound", bson.D{ 28 {"should", bson.A{ 29 bson.D{ 30 {"autocomplete", bson.D{{"query", "pri"}, {"path", "title"}}}, 31 }, 32 bson.D{ 33 {"autocomplete", bson.D{{"query", "pri"}, {"path", "plot"}}}, 34 }, 35 }}, 36 {"minimumShouldMatch", 1}, 37 }}, 38 }}, 39 } 40 limitStage := bson.D{{"$limit", 5}} 41 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"plot", 1}, {"_id", 0}}}} 42 // run pipeline 43 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage}) 44 if err != nil { 45 panic(err) 46 } 47 48 // print results 49 var results []bson.D 50 if err = cursor.All(context.TODO(), &results); err != nil { 51 panic(err) 52 } 53 for _, result := range results { 54 fmt.Println(result) 55 } 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 following command to query your collection:
go run autocomplete-query.go [ {plot Prison Terminal: The Last Days of Private Jack Hall is a moving cinema verite documentary that breaks through the walls of one of Americas oldest maximum security prisons to tell the story ...} {title Prison Terminal: The Last Days of Private Jack Hall} ] [ {plot Now settled in Genovia, Princess Mia faces a new revelation: she is being primed for an arranged marriage to an English suitor.} {title The Princess Diaries 2: Royal Engagement} ] [ {plot A young fugitive prince and princess must stop a villain who unknowingly threatens to destroy the world with a special dagger that enables the magic sand inside to reverse time.} {title Prince of Persia: The Sands of Time} ] [ {plot The first wedding anniversary of Princess Odette and Prince Derek is distracted by field fires set by Knuckles. His master Clavius, wants to conquer the world, and he needs to capture a ...} {title The Swan Princess: Escape from Castle Mountain} ] [ {plot Jane Austen's classic novel about the prejudice that occurred between the 19th century classes and the pride which would keep lovers apart.} {title Pride and Prejudice} ]
In these results, the characters pri
appear at the beginning of a word in
all the titles and plots. Atlas Search returns results that begin with the specified
query string because the title
and plot
fields are indexed using the
edgeGram
tokenization strategy.
In this section, you will connect to your Atlas cluster and run the sample
queries against the title
field in the sample_mflix.movies
collection
using the autocomplete
operator. This sample query uses a sequence of
characters to find movie titles that include words that begin with the input
character string.
Run an Atlas Search query with the autocomplete
operator on the movies
collection.
Create a file named
AutocompleteQuery.java
.Copy and paste the following code into the
AutocompleteQuery.java
file.The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
1 import static com.mongodb.client.model.Aggregates.limit; 2 import static com.mongodb.client.model.Aggregates.project; 3 import static com.mongodb.client.model.Projections.excludeId; 4 import static com.mongodb.client.model.Projections.fields; 5 import static com.mongodb.client.model.Projections.include; 6 import com.mongodb.client.MongoClient; 7 import com.mongodb.client.MongoClients; 8 import com.mongodb.client.MongoCollection; 9 import com.mongodb.client.MongoDatabase; 10 import org.bson.Document; 11 import java.util.Arrays; 12 13 public class AutocompleteQuery { 14 15 public static void main(String[] args) { 16 // connect to your Atlas cluster 17 String uri = "<connection-string>"; 18 19 try (MongoClient mongoClient = MongoClients.create(uri)) { 20 // set namespace 21 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 22 MongoCollection<Document> collection = database.getCollection("movies"); 23 24 // define pipeline 25 Document agg = new Document("$search", 26 new Document("index", "autocomplete-tutorial") 27 .append("autocomplete", new Document("query", "ger").append("path", "title"))); 28 // run pipeline and print results 29 collection.aggregate(Arrays.asList(agg, 30 limit(20), 31 project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson())); 32 } 33 } 34 } 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
AutocompleteQuery.java
file.javac AutocompleteQuery.java java AutocompleteQuery {"title": "Gertie the Dinosaur"} {"title": "Germany Year Zero"} {"title": "Germany in Autumn"} {"title": "Germany Pale Mother"} {"title": "Gerhard Richter - Painting"} {"title": "Geronimo: An American Legend"} {"title": "How to Live in the German Federal Republic"} {"title": "Geri's Game"} {"title": "The Gerson Miracle"} {"title": "The German Doctor"} {"title": "From Caligari to Hitler: German Cinema in the Age of the Masses"} {"title": "From Caligari to Hitler: German Cinema in the Age of the Masses"} {"title": "Gèraldine"} {"title": "Gervaise"} {"title": "Gertrud"} {"title": "Germinal"} {"title": "Gerry"} {"title": "Gerontophilia"} {"title": "Pionery-geroi"} {"title": "The Good German"}
In these results, the characters ger
appear at the beginning of a word in
all the titles. Atlas Search returns results that begin with the specified query
string because the title
field is indexed using the edgeGram
tokenization strategy. Atlas Search includes Gèraldine
and Rece do gèry
in
the results because we set foldDiacritics
to true
.
In this section, you will connect to your Atlas cluster and run the sample
queries against the title
and plot
fields in the
sample_mflix.movies
collection using the autocomplete
and compound
operators. This sample query uses a sequence of characters to find movie
titles and corresponding plots with words that begin with the same input
character string.
Run an Atlas Search query with the autocomplete
operator on the movies
collection.
Create a file named
AutocompleteQuery.java
.Copy and paste the following code into the
AutocompleteQuery.java
file.The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
1 import static com.mongodb.client.model.Aggregates.limit; 2 import static com.mongodb.client.model.Aggregates.project; 3 import static com.mongodb.client.model.Projections.excludeId; 4 import static com.mongodb.client.model.Projections.fields; 5 import static com.mongodb.client.model.Projections.include; 6 import com.mongodb.client.MongoClient; 7 import com.mongodb.client.MongoClients; 8 import com.mongodb.client.MongoCollection; 9 import com.mongodb.client.MongoDatabase; 10 import org.bson.Document; 11 import java.util.Arrays; 12 13 public class AutocompleteQuery { 14 15 public static void main(String[] args) { 16 // connect to your Atlas cluster 17 String uri = "<connection-string>"; 18 19 try (MongoClient mongoClient = MongoClients.create(uri)) { 20 // set namespace 21 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 22 MongoCollection<Document> collection = database.getCollection("movies"); 23 24 // define pipeline 25 Document agg = new Document("$search", 26 new Document("index", "autocomplete-tutorial") 27 .append("compound", 28 new Document("should", Arrays.asList(new Document("autocomplete", 29 new Document("query", "pri") 30 .append("path", "title")), 31 new Document("autocomplete", 32 new Document("query", "pri") 33 .append("path", "plot")))) 34 .append("minimumShouldMatch", 1L))); 35 // run pipeline and print results 36 collection.aggregate(Arrays.asList(agg, 37 limit(5), 38 project(fields(excludeId(), include("title"))))).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
AutocompleteQuery.java
file.javac AutocompleteQuery.java java AutocompleteQuery { plot: 'Prison Terminal: The Last Days of Private Jack Hall is a moving cinema verite documentary that breaks through the walls of one of Americas oldest maximum security prisons to tell the story ...', title: 'Prison Terminal: The Last Days of Private Jack Hall' } { plot: 'Now settled in Genovia, Princess Mia faces a new revelation: she is being primed for an arranged marriage to an English suitor.', title: 'The Princess Diaries 2: Royal Engagement' } { plot: 'A young fugitive prince and princess must stop a villain who unknowingly threatens to destroy the world with a special dagger that enables the magic sand inside to reverse time.', title: 'Prince of Persia: The Sands of Time' } { plot: 'The first wedding anniversary of Princess Odette and Prince Derek is distracted by field fires set by Knuckles. His master Clavius, wants to conquer the world, and he needs to capture a ...', title: 'The Swan Princess: Escape from Castle Mountain' } { plot: "Jane Austen's classic novel about the prejudice that occurred between the 19th century classes and the pride which would keep lovers apart.", title: 'Pride and Prejudice' }
In these results, the characters pri
appear at the beginning of a word in
all the titles and plots. Atlas Search returns results that begin with the specified
query string because the title
and plot
fields are indexed using the
edgeGram
tokenization strategy.
In this section, you will connect to your Atlas cluster and run the sample
queries against the title
field in the sample_mflix.movies
collection
using the autocomplete
operator. This sample query uses a sequence of
characters to find movie titles that include words that begin with the input
character string.
Run an Atlas Search query with the autocomplete
operator on the movies
collection.
Create a file named
AutocompleteQuery.kt
.Copy and paste the following code into the
AutocompleteQuery.kt
file.The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
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 // connect to your Atlas cluster 10 val uri = "<connection-string>" 11 val mongoClient = MongoClient.create(uri) 12 13 // set namespace 14 val database = mongoClient.getDatabase("sample_mflix") 15 val collection = database.getCollection<Document>("movies") 16 17 runBlocking { 18 // define pipeline 19 val agg = Document( 20 "\$search", 21 Document("index", "autocomplete-tutorial") 22 .append("autocomplete", Document("query", "ger").append("path", "title")) 23 ) 24 25 // run pipeline and print results 26 val resultsFlow = collection.aggregate<Document>( 27 listOf( 28 agg, 29 limit(20), 30 project(fields(excludeId(), include("title"))) 31 ) 32 ) 33 resultsFlow.collect { println(it) } 34 } 35 mongoClient.close() 36 } 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
AutocompleteQuery.kt
file.When you run the
AutocompleteQuery.kt
program in your IDE, it prints the following documents:Document{{title=Germany in Autumn}} Document{{title=Germany Pale Mother}} Document{{title=Gertie the Dinosaur}} Document{{title=Geronimo: An American Legend}} Document{{title=How to Live in the German Federal Republic}} Document{{title=Geri's Game}} Document{{title=The Gerson Miracle}} Document{{title=The German Doctor}} Document{{title=From Caligari to Hitler: German Cinema in the Age of the Masses}} Document{{title=From Caligari to Hitler: German Cinema in the Age of the Masses}} Document{{title=Gervaise}} Document{{title=Germinal}} Document{{title=Gerry}} Document{{title=Gèraldine}} Document{{title=Pionery-geroi}} Document{{title=Rece do gèry}} Document{{title=The Good German}} Document{{title=Berlin Is in Germany}} Document{{title=Almanya: Welcome to Germany}} Document{{title=Hitler: A Film from Germany}}
In these results, the characters ger
appear at the beginning of a word in
all the titles. Atlas Search returns results that begin with the specified query
string because the title
field is indexed using the edgeGram
tokenization strategy. Atlas Search includes Gèraldine
and Rece do gèry
in
the results because we set foldDiacritics
to true
.
In this section, you will connect to your Atlas cluster and run the sample
queries against the title
and plot
fields in the
sample_mflix.movies
collection using the autocomplete
and compound
operators. This sample query uses a sequence of characters to find movie
titles and corresponding plots with words that begin with the same input
character string.
Run an Atlas Search query with the autocomplete
operator on the movies
collection.
Create a file named
AutocompleteQuery.kt
.Copy and paste the following code into the
AutocompleteQuery.kt
file.The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
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 // connect to your Atlas cluster 10 val uri = "<connection-string>" 11 val mongoClient = MongoClient.create(uri) 12 13 // set namespace 14 val database = mongoClient.getDatabase("sample_mflix") 15 val collection = database.getCollection<Document>("movies") 16 17 runBlocking { 18 // define pipeline 19 val agg = Document( 20 "\$search", 21 Document("index", "autocomplete-tutorial") 22 .append( 23 "compound", 24 Document( 25 "should", listOf( 26 Document( 27 "autocomplete", 28 Document("query", "pri") 29 .append("path", "title") 30 ), 31 Document( 32 "autocomplete", 33 Document("query", "pri") 34 .append("path", "plot") 35 ) 36 ) 37 ) 38 .append("minimumShouldMatch", 1L) 39 ) 40 ) 41 42 // run pipeline and print results 43 val resultsFlow = collection.aggregate<Document>( 44 listOf( 45 agg, 46 limit(5), 47 project(fields(excludeId(), include("title", "plot"))) 48 ) 49 ) 50 resultsFlow.collect { println(it) } 51 } 52 mongoClient.close() 53 } 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
AutocompleteQuery.kt
file.When you run the
AutocompleteQuery.kt
program in your IDE, it prints the following documents:Document{{plot=Prison Terminal: The Last Days of Private Jack Hall is a moving cinema verite documentary that breaks through the walls of one of Americas oldest maximum security prisons to tell the story ..., title=Prison Terminal: The Last Days of Private Jack Hall}} Document{{plot=Now settled in Genovia, Princess Mia faces a new revelation: she is being primed for an arranged marriage to an English suitor., title=The Princess Diaries 2: Royal Engagement}} Document{{plot=A young fugitive prince and princess must stop a villain who unknowingly threatens to destroy the world with a special dagger that enables the magic sand inside to reverse time., title=Prince of Persia: The Sands of Time}} Document{{plot=The first wedding anniversary of Princess Odette and Prince Derek is distracted by field fires set by Knuckles. His master Clavius, wants to conquer the world, and he needs to capture a ..., title=The Swan Princess: Escape from Castle Mountain}} Document{{plot=Jane Austen's classic novel about the prejudice that occurred between the 19th century classes and the pride which would keep lovers apart., title=Pride and Prejudice}}
In these results, the characters pri
appear at the beginning of a word in
all the titles and plots. Atlas Search returns results that begin with the specified
query string because the title
and plot
fields are indexed using the
edgeGram
tokenization strategy.
In this section, you will connect to your Atlas cluster and run the sample
queries against the title
field in the sample_mflix.movies
collection
using the autocomplete
operator. This sample query uses a sequence of
characters to find movie titles that include words that begin with the input
character string.
Run an Atlas Search query with the autocomplete
operator on the movies
collection.
Create a file named
autocomplete-query.js
.Copy and paste the following code into the
autocomplete-query.js
file.The code example performs 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.Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas cluster 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async function run() { 10 try { 11 await client.connect(); 12 13 // set namespace 14 const database = client.db("sample_mflix"); 15 const coll = database.collection("movies"); 16 17 // define pipeline 18 const agg = [ 19 {$search: {index: "autocomplete-tutorial", autocomplete: {query: "ger", path: "title"}}}, 20 {$limit: 20}, 21 {$project: {_id: 0,title: 1}} 22 ]; 23 // run pipeline 24 const result = await coll.aggregate(agg); 25 26 // print results 27 await result.forEach((doc) => console.log(doc)); 28 } finally { 29 await client.close(); 30 } 31 } 32 run().catch(console.dir); 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:
node autocompelte-query.js { title: 'Gertie the Dinosaur' } { title: 'Germany Year Zero' } { title: 'Germany in Autumn' } { title: 'Germany Pale Mother' } { title: 'Gerhard Richter - Painting' } { title: 'Geronimo: An American Legend' } { title: 'How to Live in the German Federal Republic' } { title: "Geri's Game" } { title: 'The Gerson Miracle' } { title: 'The German Doctor' } { title: 'From Caligari to Hitler: German Cinema in the Age of the Masses' } { title: 'From Caligari to Hitler: German Cinema in the Age of the Masses' } { title: 'Gèraldine' } { title: 'Gervaise' } { title: 'Gertrud' } { title: 'Germinal' } { title: 'Gerry' } { title: 'Gerontophilia' } { title: 'Pionery-geroi' } { title: 'The Good German' }
In these results, the characters ger
appear at the beginning of a word in
all the titles. Atlas Search returns results that begin with the specified query
string because the title
field is indexed using the edgeGram
tokenization strategy. Atlas Search includes Gèraldine
and Rece do gèry
in
the results because we set foldDiacritics
to true
.
In this section, you will connect to your Atlas cluster and run the sample
queries against the title
and plot
fields in the
sample_mflix.movies
collection using the autocomplete
and compound
operators. This sample query uses a sequence of characters to find movie
titles and corresponding plots with words that begin with the same input
character string.
Run an Atlas Search query with the autocomplete
operator on the movies
collection.
Create a file named
autocomplete-query.js
.Copy and paste the following code into the
autocomplete-query.js
file.The code example performs 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.Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas cluster 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async function run() { 10 try { 11 await client.connect(); 12 13 // set namespace 14 const database = client.db("sample_mflix"); 15 const coll = database.collection("movies"); 16 17 // define pipeline 18 const agg = [ 19 { 20 '$search': { 21 'index': 'autocomplete-tutorial', 22 'compound': { 23 'should': [ 24 { 25 'autocomplete': { 26 'query': 'pri', 27 'path': 'title' 28 } 29 }, 30 { 31 'autocomplete': { 32 'query': 'pri', 33 'path': 'plot' 34 } 35 } 36 ], 37 'minimumShouldMatch': 1 38 } 39 } 40 }, 41 { 42 '$limit': 5 43 }, 44 { 45 '$project': { 46 '_id': 0, 47 'title': 1, 48 'plot': 1 49 } 50 } 51 ]; 52 // run pipelines 53 const result = await coll.aggregate(agg); 54 55 // print results 56 await result.forEach((doc) => console.log(doc)); 57 } finally { 58 await client.close(); 59 } 60 } 61 run().catch(console.dir); 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:
node autocomplete-query.js { plot: 'Prison Terminal: The Last Days of Private Jack Hall is a moving cinema verite documentary that breaks through the walls of one of Americas oldest maximum security prisons to tell the story ...', title: 'Prison Terminal: The Last Days of Private Jack Hall' } { plot: 'Now settled in Genovia, Princess Mia faces a new revelation: she is being primed for an arranged marriage to an English suitor.', title: 'The Princess Diaries 2: Royal Engagement' } { plot: 'A young fugitive prince and princess must stop a villain who unknowingly threatens to destroy the world with a special dagger that enables the magic sand inside to reverse time.', title: 'Prince of Persia: The Sands of Time' } { plot: 'The first wedding anniversary of Princess Odette and Prince Derek is distracted by field fires set by Knuckles. His master Clavius, wants to conquer the world, and he needs to capture a ...', title: 'The Swan Princess: Escape from Castle Mountain' } { plot: "Jane Austen's classic novel about the prejudice that occurred between the 19th century classes and the pride which would keep lovers apart.", title: 'Pride and Prejudice' }
In these results, the characters pri
appear at the beginning of a word in
all the titles and plots. Atlas Search returns results that begin with the specified
query string because the title
and plot
fields are indexed using the
edgeGram
tokenization strategy.
In this section, you will connect to your Atlas cluster and run the sample
queries against the title
field in the sample_mflix.movies
collection
using the autocomplete
operator. This sample query uses a sequence of
characters to find movie titles that include words that begin with the input
character string.
Run an Atlas Search query with the autocomplete
operator on the movies
collection.
Create a file named
autocomplete-query.py
.Copy and paste the following code into the
autocomplete.py
file.The following code example:
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.Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
1 import pymongo 2 3 # connect to your Atlas cluster 4 client = pymongo.MongoClient('<connection-string>') 5 6 # define pipeline 7 pipeline = [ 8 {"$search": {"index": "autocomplete-tutorial", "autocomplete": {"query": "ger", "path": "title"}}}, 9 {"$limit": 20}, 10 {"$project": {"_id": 0, "title": 1}}, 11 ] 12 # run pipeline 13 result = client["sample_mflix"]["movies"].aggregate(pipeline) 14 15 # print results 16 for i in result: 17 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. To learn more, see Connect via Drivers.Run the following command to query your collection:
python autocomplete-query.py {'title': 'Gertie the Dinosaur'} {'title': 'Germany Year Zero'} {'title': 'Germany in Autumn'} {'title': 'Germany Pale Mother'} {'title': 'Gerhard Richter - Painting'} {'title': 'Geronimo: An American Legend'} {'title': 'How to Live in the German Federal Republic'} {'title': "Geri's Game"} {'title': 'The Gerson Miracle'} {'title': 'The German Doctor'} {'title': 'From Caligari to Hitler: German Cinema in the Age of the Masses'} {'title': 'From Caligari to Hitler: German Cinema in the Age of the Masses'} {'title': 'G\xe8raldine'} {'title': 'Gervaise'} {'title': 'Gertrud'} {'title': 'Germinal'} {'title': 'Gerry'} {'title': 'Gerontophilia'} {'title': 'Pionery-geroi'} {'title': 'The Good German'}
In these results, the characters ger
appear at the beginning of a word in
all the titles. Atlas Search returns results that begin with the specified query
string because the title
field is indexed using the edgeGram
tokenization strategy. Atlas Search includes Gèraldine
and Rece do gèry
in
the results because we set foldDiacritics
to true
.
In this section, you will connect to your Atlas cluster and run the sample
queries against the title
and plot
fields in the
sample_mflix.movies
collection using the autocomplete
and compound
operators. This sample query uses a sequence of characters to find movie
titles and corresponding plots with words that begin with the same input
character string.
Run an Atlas Search query with the autocomplete
operator on the movies
collection.
Create a file named
autocomplete-query.py
.Copy and paste the following code into the
autocomplete.py
file.The following code example:
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.Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
1 import pymongo 2 3 # connect to your Atlas cluster 4 client = pymongo.MongoClient('<connection-string>') 5 6 # define pipeline 7 pipeline = [ 8 { 9 '$search': { 10 'index': 'autocomplete-tutorial', 11 'compound': { 12 'should': [ 13 { 14 'autocomplete': { 15 'query': 'pri', 16 'path': 'title' 17 } 18 }, { 19 'autocomplete': { 20 'query': 'pri', 21 'path': 'plot' 22 } 23 } 24 ], 25 'minimumShouldMatch': 1 26 } 27 } 28 }, 29 { 30 '$limit': 5 31 }, 32 { 33 '$project': { 34 '_id': 0, 'title': 1, 'plot': 1 35 } 36 } 37 ] 38 # run pipeline 39 result = client["sample_mflix"]["movies"].aggregate(pipeline) 40 41 # print results 42 for i in result: 43 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. To learn more, see Connect via Drivers.Run the following command to query your collection:
python autocomplete-query.py { plot: 'Prison Terminal: The Last Days of Private Jack Hall is a moving cinema verite documentary that breaks through the walls of one of Americas oldest maximum security prisons to tell the story ...', title: 'Prison Terminal: The Last Days of Private Jack Hall' } { plot: 'Now settled in Genovia, Princess Mia faces a new revelation: she is being primed for an arranged marriage to an English suitor.', title: 'The Princess Diaries 2: Royal Engagement' } { plot: 'A young fugitive prince and princess must stop a villain who unknowingly threatens to destroy the world with a special dagger that enables the magic sand inside to reverse time.', title: 'Prince of Persia: The Sands of Time' } { plot: 'The first wedding anniversary of Princess Odette and Prince Derek is distracted by field fires set by Knuckles. His master Clavius, wants to conquer the world, and he needs to capture a ...', title: 'The Swan Princess: Escape from Castle Mountain' } { plot: "Jane Austen's classic novel about the prejudice that occurred between the 19th century classes and the pride which would keep lovers apart.", title: 'Pride and Prejudice' }
In these results, the characters pri
appear at the beginning of a word in
all the titles and plots. Atlas Search returns results that begin with the specified
query string because the title
and plot
fields are indexed using the
edgeGram
tokenization strategy.