Docs Menu
Docs Home
/
MongoDB Atlas
/ /

How to Use Autocomplete with Atlas Search

On this page

  • Define an Index with Autocomplete
  • Run an Autocomplete Query

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:

  1. Set up an Atlas Search index with autocomplete data type for the sample_mflix.movies collection.

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

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.

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

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

  3. If the Clusters page is not already displayed, click Database in the sidebar.

    The Clusters page displays.

2

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

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

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

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

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

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

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

    Note

    If you name your index default, you don't need to specify an index parameter when using the $search pipeline stage. Otherwise, you must specify the index name using the index parameter.

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

6

You can use the Atlas Search Visual Editor or the Atlas Search JSON Editor in the Atlas user interface to create the index.

  1. Click Next.

  2. Click Refine Your Index.

  3. Click Add Field in the Field Mappings section.

  4. Click Quick Start for Text Fields if it's not already selected and select Search-as-you-type template from the dropdown.

  5. Select title from the Field Name dropdown.

  6. Click Add.

  7. Repeat steps c through e for the plot field.

  8. Click Save Changes.

  1. 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
    }
    }
    }
    }
  2. Click Next.

7
8

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

9

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


Use the Select your language drop-down menu to set the language of the 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.

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

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

  3. If the Clusters page is not already displayed, click Database in the sidebar.

    The Clusters page displays.

2

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

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

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

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3

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

4

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

5

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
6

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

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.

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

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

  3. If the Clusters page is not already displayed, click Database in the sidebar.

    The Clusters page displays.

2

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

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

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

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3

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

4

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

5

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
6

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

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.

1

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

2

Run the following command at mongosh prompt:

use sample_mflix
3

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.

1

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

2

Run the following command at mongosh prompt:

use sample_mflix
3

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.

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

1

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

2

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

3

The query uses the following pipeline stages:

  • $search to search the title field using the autocomplete operator for words that begin with the characters ger

  • $limit stage to limit the output to 20 results

  • $project stage to exclude all fields except title

To run this query in MongoDB Compass:

  1. Click the Aggregations tab.

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

    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 Stage
    Query
    $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.

1

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

2

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

3

The query uses the following pipeline stages:

  • $search to search the title and plot fields using the autocomplete operator for words that begin with the characters pri

  • $limit stage to limit the output to 5 results

  • $project stage to exclude all fields except title and plot

To run this query in MongoDB Compass:

  1. Click the Aggregations tab.

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

    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 Stage
    Query
    $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.

1
  1. Create a new directory called basic-autocomplete-example and initialize your project with the dotnet new command.

    mkdir basic-autocomplete-example
    cd basic-autocomplete-example
    dotnet new console
  2. Add the .NET/C# Driver to your project as a dependency.

    dotnet add package MongoDB.Driver
2
  1. 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:

      • $search to search the title field using the autocomplete operator for words that begin with the characters ger

      • $limit stage to limit the output to 20 results

      • $project stage to exclude all fields except title

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

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public 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[BsonIgnoreExtraElements]
    40public class MovieDocument
    41{
    42 [BsonIgnoreIfDefault]
    43 public ObjectId Id { get; set; }
    44 public string Title { get; set; }
    45}
  2. 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.

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

1
  1. Create a new directory called advanced-autocomplete-example and initialize your project with the dotnet new command.

    mkdir advanced-autocomplete-example
    cd advanced-autocomplete-example
    dotnet new console
  2. Add the .NET/C# Driver to your project as a dependency.

    dotnet add package MongoDB.Driver
2
  1. 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:

      • $search to search the title and plot fields using the autocomplete operator for words that begin with the characters pri

      • $limit stage to limit the output to 5 results

      • $project stage to exclude all fields except title and plot

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

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public 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[BsonIgnoreExtraElements]
    45public class MovieDocument
    46{
    47 [BsonIgnoreIfDefault]
    48 public ObjectId Id { get; set; }
    49 public string Plot { get; set; }
    50 public string Title { get; set; }
    51}
  2. 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.

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

1
  1. Create a file named autocomplete-query.go.

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

      • $search to search the title field using the autocomplete operator for words that begin with the characters ger

      • $limit stage to limit the output to 20 results

      • $project stage to exclude all fields except title

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

    1package main
    2
    3import (
    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
    12func 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}
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Run the following command to query your collection:

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

1
  1. Create a file named autocomplete-query.go.

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

      • $search to search the title and plot fields using the autocomplete operator for words that begin with the characters pri

      • $limit stage to limit the output to 5 results

      • $project stage to exclude all fields except title and plot

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

    1package main
    2
    3import (
    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
    12func 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}
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Run the following command to query your collection:

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

1
junit
4.11 or higher version
mongodb-driver-sync
4.3.0 or higher version
slf4j-log4j12
1.7.30 or higher version
2
  1. Create a file named AutocompleteQuery.java.

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

      • $search to search the title field using the autocomplete operator for words that begin with the characters ger

      • $limit stage to limit the output to 20 results

      • $project stage to exclude all fields except title

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

    1import static com.mongodb.client.model.Aggregates.limit;
    2import static com.mongodb.client.model.Aggregates.project;
    3import static com.mongodb.client.model.Projections.excludeId;
    4import static com.mongodb.client.model.Projections.fields;
    5import static com.mongodb.client.model.Projections.include;
    6import com.mongodb.client.MongoClient;
    7import com.mongodb.client.MongoClients;
    8import com.mongodb.client.MongoCollection;
    9import com.mongodb.client.MongoDatabase;
    10import org.bson.Document;
    11import java.util.Arrays;
    12
    13public 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;
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Compile and run 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.

1
junit
4.11 or higher version
mongodb-driver-sync
4.3.0 or higher version
slf4j-log4j12
1.7.30 or higher version
2
  1. Create a file named AutocompleteQuery.java.

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

      • $search to search the title and plot fields using the autocomplete operator for words that begin with the characters pri

      • $limit stage to limit the output to 5 results

      • $project stage to exclude all fields except title and plot

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

    1import static com.mongodb.client.model.Aggregates.limit;
    2import static com.mongodb.client.model.Aggregates.project;
    3import static com.mongodb.client.model.Projections.excludeId;
    4import static com.mongodb.client.model.Projections.fields;
    5import static com.mongodb.client.model.Projections.include;
    6import com.mongodb.client.MongoClient;
    7import com.mongodb.client.MongoClients;
    8import com.mongodb.client.MongoCollection;
    9import com.mongodb.client.MongoDatabase;
    10import org.bson.Document;
    11import java.util.Arrays;
    12
    13public 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;
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Compile and run 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.

1
mongodb-driver-kotlin-coroutine
4.10.0 or higher version
2
  1. Create a file named AutocompleteQuery.kt.

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

      • $search to search the title field using the autocomplete operator for words that begin with the characters ger

      • $limit stage to limit the output to 20 results

      • $project stage to exclude all fields except title

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

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Projections.*
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7
    8fun main() {
    9 // 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}
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

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

1
mongodb-driver-kotlin-coroutine
4.10.0 or higher version
2
  1. Create a file named AutocompleteQuery.kt.

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

      • $search to search the title and plot fields using the autocomplete operator for words that begin with the characters pri

      • $limit stage to limit the output to 5 results

      • $project stage to exclude all fields except title and plot

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

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Projections.*
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7
    8fun main() {
    9 // 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}
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

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

1
  1. Create a file named autocomplete-query.js.

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

      • $search to search the title field using the autocomplete operator for words that begin with the characters ger

      • $limit stage to limit the output to 20 results

      • $project stage to exclude all fields except title

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

    1const { MongoClient } = require("mongodb");
    2
    3// connect to your Atlas cluster
    4const uri =
    5 "<connection-string>";
    6
    7const client = new MongoClient(uri);
    8
    9async 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}
    32run().catch(console.dir);
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Run the following command to query your collection:

    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.

1
  1. Create a file named autocomplete-query.js.

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

      • $search to search the title and plot fields using the autocomplete operator for words that begin with the characters pri

      • $limit stage to limit the output to 5 results

      • $project stage to exclude all fields except title and plot

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

    1const { MongoClient } = require("mongodb");
    2
    3// connect to your Atlas cluster
    4const uri =
    5 "<connection-string>";
    6
    7const client = new MongoClient(uri);
    8
    9async 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}
    61run().catch(console.dir);
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

  4. Run the following command to query your collection:

    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.

1
  1. Create a file named autocomplete-query.py.

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

    The following code example:

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

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

    • Uses the following pipeline stages:

      • $search to search the title field using the autocomplete operator for words that begin with the characters ger

      • $limit stage to limit the output to 20 results

      • $project stage to exclude all fields except title

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

    1import pymongo
    2
    3# connect to your Atlas cluster
    4client = pymongo.MongoClient('<connection-string>')
    5
    6# define pipeline
    7pipeline = [
    8 {"$search": {"index": "autocomplete-tutorial", "autocomplete": {"query": "ger", "path": "title"}}},
    9 {"$limit": 20},
    10 {"$project": {"_id": 0, "title": 1}},
    11]
    12# run pipeline
    13result = client["sample_mflix"]["movies"].aggregate(pipeline)
    14
    15# print results
    16for i in result:
    17 print(i)
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

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

1
  1. Create a file named autocomplete-query.py.

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

    The following code example:

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

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

    • Uses the following pipeline stages:

      • $search to search the title and plot fields using the autocomplete operator for words that begin with the characters pri

      • $limit stage to limit the output to 5 results

      • $project stage to exclude all fields except title and plot

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

    1import pymongo
    2
    3# connect to your Atlas cluster
    4client = pymongo.MongoClient('<connection-string>')
    5
    6# define pipeline
    7pipeline = [
    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
    39result = client["sample_mflix"]["movies"].aggregate(pipeline)
    40
    41# print results
    42for i in result:
    43 print(i)
  3. Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

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

Back

How to Sort Your

Next

Facets