autocomplete

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

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

Available tabs: other tabs: edgeGram, rightEdgeGram, nGram, fts-vs, data-explorer -->

autocomplete Operator

Definition

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. To learn how to configure your index for autocompletion, see [How to Index Fields for Autocompletion.](https://www.mongodb.com/docs/search/indexes/field-types/autocomplete-type.md#std-label-bson-data-types-autocomplete

Note:

MongoDB Search might return inaccurate results for queries with more than three words in a single string.

Sample Use Cases

You can use the autocomplete operator with search-as-you-type applications to predict words with increasing accuracy as characters are entered in your application's search field. autocomplete returns results that contain predicted words based on the tokenization strategy specified in the index definition for autocompletion.

If you want to build suggestions or dropdowns using the MongoDB Search autocomplete operator, we recommend that you query a collection of suggested search terms or use past search terms to populate the dropdown. If you create a separate collection of suggested search terms, you can [define synonym mappings in your MongoDB Search index](https://www.mongodb.com/docs/search/indexes/synonyms.md#std-label-synonyms-ref to search your collection for the exact or alternative words.

Syntax

autocomplete has the following syntax:

{
  $search: {
    "index": "<index name>", // optional, defaults to "default"
    "autocomplete": {
      "query": "<search-string>",
      "path": "<field-to-search>",
      "tokenOrder": "any|sequential",
      "fuzzy": <options>,
      "score": <options>
    }
  }
}

Options

Field Type Description Necessity Default
query string or array of strings String or strings to search for. If there are multiple terms in a string, MongoDB Search also looks for a match for each term in the string separately. yes
path string Indexed field to search. This field must be indexed as the autocomplete data type. To learn more, see How to Index Fields for Autocompletion.d yes
fuzzy object Enable fuzzy search. Find strings which are similar to the search term or terms. no
fuzzy``.maxEdits integer Maximum number of single-character edits required to match the specified search term. Value can be 1 or 2. no 2
fuzzy``.prefixLength integer Number of characters at the beginning of each term in the result that must exactly match. no 0
fuzzy``.maxExpansions integer Maximum number of variations to generate and search for. This limit applies on a per-token basis. no 50
score object [Score](https://www.mongodb.com/docs/search/query/score/overview.md#std-label-scoring-ref to assign to the matching search term results. Use one of the following options to modify the default score: boost: Multiply the result score by the given number.; constant: Replace the result score with the given number.; function: Replace the result score with the given expression. autocomplete offers less fidelity in [score](https://www.mongodb.com/docs/search/query/score/overview.md#std-label-scoring-ref in exchange for faster query execution. To learn more, see [Scoring Behavior.](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-scoring-behavior For information on using score in your query, see [Score the Documents in the Results.](https://www.mongodb.com/docs/search/query/score/overview.md#std-label-scoring-ref no
tokenOrder string Order in which to search for tokens. Value can be one of the following: any: Indicates tokens in the query can appear in any order in the documents. Results contain documents where the tokens appear sequentially and non-sequentially. However, results where the tokens appear sequentially score higher than other, non-sequential values.; sequential: Indicates tokens in the query must appear adjacent to each other or in the order specified in the query in the documents. Results contain only documents where the tokens appear sequentially. no any

Scoring Behavior

By default, the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator uses the bm25 similarity algorithm to score documents depending on their relevance to the query.

You can change which similarity algorithm is used by specifying a different similarity algorithm in the similarity.type property for the autocomplete fields in your MongoDB Search index definition. To learn how to configure a MongoDB Search index for the autocomplete type, see [How to Index String Fields](https://www.mongodb.com/docs/search/indexes/field-types/string-type.md#std-label-bson-data-types-string.

To learn more about the supported similarity algorithms, see [Score Details.](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms

The autocomplete operator query results that are exact matches receive a lower score than results that aren't exact matches. MongoDB Search can't determine if a query string is an exact match for an indexed text if you specify just the autocomplete-indexed token substrings. To score exact matches higher, try the following workaround:

Note:

The following workaround doesn't guarantee higher scores for exact matches in all cases.

  1. Index the field as both [autocomplete](https://www.mongodb.com/docs/search/indexes/field-types/autocomplete-type.md#std-label-bson-data-types-autocomplete and [string](https://www.mongodb.com/docs/search/indexes/field-types/string-type.md#std-label-bson-data-types-string types.

MongoDB Search autocomplete boosts exact matches when an autocomplete field is also indexed as a string, thereby increasing the score of exact matches.

  1. Query using the [compound operator.](https://www.mongodb.com/docs/search/query/operators-collectors/compound.md#std-label-compound-ref

For a demonstration of this workaround, see [Search Across Multiple Fields.](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-compound

Examples

The following examples use the movies collection in the sample_mflix database. If you loaded the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets on your cluster, you can create the static index for [autocompletion](https://www.mongodb.com/docs/search/indexes/field-types/autocomplete-type.md#std-label-bson-data-types-autocomplete and run the example queries on your cluster.

Index Definition

The following tabs contain sample index definitions for the edgeGram, rightEdgeGram, and nGram [tokenization strategies](https://www.mongodb.com/docs/search/indexes/field-types/autocomplete-type.md#std-label-bson-data-types-autocomplete. In addition to the [autocomplete](https://www.mongodb.com/docs/search/indexes/field-types/autocomplete-type.md#std-label-bson-data-types-autocomplete type, the sample index definitions include the [string](https://www.mongodb.com/docs/search/indexes/field-types/string-type.md#std-label-bson-data-types-string and [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token types on the title field.

edgeGram

{
  "mappings": {
    "dynamic": false,
    "fields": {
      "title": [
        {
          "type": "token"
        },
        {
          "type": "string"
        },
        {
          "foldDiacritics": false,
          "maxGrams": 7,
          "minGrams": 3,
          "tokenization": "edgeGram",
          "type": "autocomplete"
        }
      ],
      "plot": [
        {
          "type": "autocomplete",
          "tokenization": "edgeGram",
          "minGrams": 2,
          "maxGrams": 15,
          "foldDiacritics": true
        }
      ]
    }
  }
}

➤ Use the Select your language drop-down menu to set the language of the example on this page.

To view and edit query syntax in the Search Tester:

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

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

### Search & Vector Search

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

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

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

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

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

The Search & Vector Search page displays.

  1. View and edit the query syntax.

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

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

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

use sample_mflix

To learn how to run the following queries in the [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh, see [Define Your Query.](https://www.mongodb.com/docs/search/about/searching.md#std-label-atlas-search-queries

To learn how to run the following queries in the MongoDB Compass, see [Define Your Query.](https://www.mongodb.com/docs/search/about/searching.md#std-label-atlas-search-queries

To learn how to run the following queries by using the MongoDB .NET/C# Driver, see [Define Your Query.](https://www.mongodb.com/docs/search/about/searching.md#std-label-atlas-search-queries

To learn how to run the following queries by using the MongoDB Go driver, see [Define Your Query.](https://www.mongodb.com/docs/search/about/searching.md#std-label-atlas-search-queries

To learn how to run the following queries by using the MongoDB Java driver, see [Define Your Query.](https://www.mongodb.com/docs/search/about/searching.md#std-label-atlas-search-queries

To learn how to run the following queries by using the MongoDB Kotlin driver, see [Define Your Query.](https://www.mongodb.com/docs/search/about/searching.md#std-label-atlas-search-queries

To learn how to run the following queries by using the MongoDB Node Driver, see [Define Your Query.](https://www.mongodb.com/docs/search/about/searching.md#std-label-atlas-search-queries

To learn how to run the following queries by using the PyMongo driver, see [Define Your Query.](https://www.mongodb.com/docs/search/about/searching.md#std-label-atlas-search-queries

Basic Example

The following query searches for movies with the characters off in the title field.

Copy and paste the following query into the Query Editor, and then click the Search button in the Query Editor.

[
  {
    $search: {
      autocomplete: {
        path: "title",
        query: "off"
      }
    }
  }
]

The query includes a:

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

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

db.movies.aggregate([
  {
    $search: {
      "autocomplete": {
        "path": "title",
        "query": "off"
      }
    }
  },
  {
    $limit: 10
  },
  {
    $project: {
      "_id": 0,
      "title": 1
    }
  }
])

The query includes a:

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

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

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 `{
“autocomplete”: {
“query”: “off”,
“path”: “title”
}
}`
$limit 10
$project `{
“_id”: 0,
“title”: 1,
}`

The query includes a:

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

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

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using MongoDB.Driver.Search;

public class AutocompleteBasicExample
{
    private const string MongoConnectionString = "<connection-string>";

    public static void Main(string[] args)
    {
        // allow automapping of the camelCase database fields to our MovieDocument
        var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
        ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);

        // connect to your Atlas cluster
        var mongoClient = new MongoClient(MongoConnectionString);
        var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
        var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");

        // define and run pipeline
        var results = moviesCollection.Aggregate()
            .Search(Builders<MovieDocument>.Search.Autocomplete(movie => movie.Title, "off"))
            .Project<MovieDocument>(Builders<MovieDocument>.Projection
                .Include(movie => movie.Title)
                .Exclude(movie => movie.Id))
            .Limit(10)
            .ToList();

        // print results
        foreach (var movie in results)
        {
            Console.WriteLine(movie.ToJson());
        }
    }
}

[BsonIgnoreExtraElements]
public class MovieDocument
{
    [BsonIgnoreIfDefault]
    public ObjectId Id { get; set; }
    public string Title { get; set; }
}

The query includes a:

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

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

package main

import (
    "context"
    "fmt"

    "go.mongodb.org/mongo-driver/v2/bson"
    "go.mongodb.org/mongo-driver/v2/mongo"
    "go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
    // connect to your Atlas cluster
    client, err := mongo.Connect(options.Client().ApplyURI("<connection-string>"))
    if err != nil {
        panic(err)
    }
    defer client.Disconnect(context.TODO())

    // set namespace
    collection := client.Database("sample_mflix").Collection("movies")

    // define pipeline stages
    searchStage := bson.D{{Key: "$search", Value: bson.D{{Key: "autocomplete", Value: bson.D{{Key: "query", Value: "off"}, {Key: "path", Value: "title"}}}}}}
    limitStage := bson.D{{Key: "$limit", Value: 10}}
    projectStage := bson.D{{Key: "$project", Value: bson.D{{Key: "title", Value: 1}, {Key: "_id", Value: 0}}}}
    // run pipeline
    cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
    if err != nil {
        panic(err)
    }

    // print results
    var results []bson.D
    if err = cursor.All(context.TODO(), &results); err != nil {
        panic(err)
    }
    for _, result := range results {
        fmt.Println(result)
    }
}

The query includes a:

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

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

import static com.mongodb.client.model.Aggregates.limit;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Projections.excludeId;
import static com.mongodb.client.model.Projections.fields;
import static com.mongodb.client.model.Projections.include;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;

public class AutocompleteBasicExample {
    public static void main(String[] args) {
        // connect to your Atlas cluster
        String uri = "<connection-string>";

        try (MongoClient mongoClient = MongoClients.create(uri)) {
            // set namespace
            MongoDatabase database = mongoClient.getDatabase("sample_mflix");
            MongoCollection<Document> collection = database.getCollection("movies");

            // define pipeline
            Document agg = new Document("$search", new Document("autocomplete", new Document("query", "off").append("path", "title")));
            // run pipeline and print results
            collection.aggregate(Arrays.asList(agg,
                limit(10),
                project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson()));
        }
    }
}

The query includes a:

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

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

import com.mongodb.client.model.Aggregates.limit
import com.mongodb.client.model.Aggregates.project
import com.mongodb.client.model.Projections.*
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import org.bson.Document

fun main() {
    val uri = "<connection-string>"
    val mongoClient = MongoClient.create(uri)
    val database = mongoClient.getDatabase("sample_mflix")
    val collection = database.getCollection<Document>("movies")

    runBlocking {
        val agg = Document(
            "\$search",
            Document("autocomplete", Document("query", "off")
                .append("path", "title"))
        )

        val resultsFlow = collection.aggregate<Document>(
            listOf(
                agg,
                limit(10),
                project(fields(excludeId(), include("title")))
            )
        )
        resultsFlow.collect { println(it) }
    }
    mongoClient.close()
}

The query includes a:

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

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

const { MongoClient } = require("mongodb");

// connect to your Atlas cluster
const uri =
    "<connection-string>";

const client = new MongoClient(uri);

async function run() {
    try {
        await client.connect();

        // set namespace
        const database = client.db("sample_mflix");
        const coll = database.collection("movies");

        // define pipeline
        const agg = [
            {$search: {autocomplete: {query: "off", path: "title"}}},
            {$limit: 10},
            {$project: {_id: 0,title: 1}}
        ];
        // run pipeline
        const result = await coll.aggregate(agg);

        // print results
        await result.forEach((doc) => console.log(doc));
    } finally {
        await client.close();
    }
}
run().catch(console.dir);

The query includes a:

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

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

import pymongo

## connect to your Atlas cluster
client = pymongo.MongoClient('<connection-string>')

## define pipeline
pipeline = [
    {"$search": {"autocomplete": {"query": "off", "path": "title"}}},
    {"$limit": 10},
    {"$project": {"_id": 0, "title": 1}},
]
## run pipeline
result = client["sample_mflix"]["movies"].aggregate(pipeline)

## print results
for i in result:
    print(i)

Note: Your Results May Vary

MongoDB Search returns different results depending on the tokenization strategy configured in the index definition for the [autocomplete](https://www.mongodb.com/docs/search/indexes/field-types/autocomplete-type.md#std-label-bson-data-types-autocomplete type. To learn more, see [How to Index Fields for Autocompletion.](https://www.mongodb.com/docs/search/indexes/field-types/autocomplete-type.md#std-label-bson-data-types-autocomplete

edgeGram

SCORE: 9.361787796020508  _id:  "573a13b0f29313caabd355c8"
  countries: Array
  genres: Array
  runtime: 100
  ...
  title: "Off Beat"

SCORE: 9.068204879760742  _id:  "573a13aaf29313caabd22a8c"
  fullplot: "An 11-year-old girl watches her father come down with a crippling depr…"
  imdb: Object
  year: 2003
  ...
  title: "Off the Map"

SCORE: 9.068204879760742  _id:  "573a13bef29313caabd5d208"
  plot: "With white Jewish lesbians for parents and two adopted brothers - one …"
  genres: Array
  runtime: 76
  ...
  title: "Off and Running"

SCORE: 8.742463111877441  _id:  "573a13bbf29313caabd5567"
  countries: Array
  genres: Array
  runtime: 98
  ...
  title: "Hands off Mississippi"

SCORE: 8.61273193359375  _id:  "5573a1396f29313caabce4791"
  plot: "Unable to deal with her parents, Jeannie Tyne runs away from home. Lar…"
  genres: Array
  runtime: 93
  ...
  title: "Taking Off"

SCORE: 8.61273193359375  _id:  "573a1399f29313caabced3c1"
  plot: "A travelling theater group find so much action going on behind-the-sce…"
  genres: Array
  runtime: 101
  ...
  title: "Noises Off..."

SCORE: 8.61273193359375  _id:  "573a139af29313caabcefc73"
  fullplot: "In existence for a hundred years, Grimley Colliery Brass band is as ol…"
  imdb: Object
  year: 1996
  ...
  title: "Brassed Off"

SCORE: 8.61273193359375  _id:  "573a139af29313caabcf08f5"
  fullplot: "Sean Archer, a very tough, rugged FBI Agent. Who is still grieving for…"
  imdb: Object
  year: 1997
  ...
  title: "Face/Off"

SCORE: 8.603004455566406  _id:  "573a13a9f29313caabd1ea36"
  fullplot: "Three unlikely, unsuspecting souls who come face-to-face with that mom…"
  imdb: Object
  year: 2004
  ...
  title: "Benji: Off the Leash!"

SCORE: 7.953945159912109  _id:  "573a139af29313caabcf037c"
  plot: "Desperation drives four inner-city women (Queen Latifah, Jada Pinkett …"
  genres: Array
  runtime: 123
  ...
  title: "Set it Off"

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.

edgeGram

{ title: 'Off Beat' },
{ title: 'Off the Map' },
{ title: 'Off and Running' },
{ title: 'Hands off Mississippi' },
{ title: 'Taking Off' },
{ title: 'Noises Off...' },
{ title: 'Brassed Off' },
{ title: 'Face/Off' },
{ title: 'Benji: Off the Leash!' },
{ title: 'Set It Off' }

In the above results, the characters off appear at the left side of a word in all the titles.

edgeGram

{ title: 'Off Beat' },
{ title: 'Off the Map' },
{ title: 'Off and Running' },
{ title: 'Hands off Mississippi' },
{ title: 'Taking Off' },
{ title: 'Noises Off...' },
{ title: 'Brassed Off' },
{ title: 'Face/Off' },
{ title: 'Benji: Off the Leash!' },
{ title: 'Set It Off' }

In the above results, the characters off appear at the left side of a word in all the titles.

edgeGram

{ "title": "Off Beat" }
{ "title": "Off the Map" }
{ "title": "Off and Running" }
{ "title": "Hands off Mississippi" }
{ "title": "Taking Off" }
{ "title": "Noises Off..." }
{ "title": "Brassed Off" }
{ "title": "Face/Off" }
{ "title": "Benji: Off the Leash!" }
{ "title": "Set It Off" }

In the above results, the characters off appear at the left side of a word in all the titles.

edgeGram

[{title Off Beat}]
[{title Off the Map}]
[{title Off and Running}]
[{title Hands off Mississippi}]
[{title Taking Off}]
[{title Noises Off...}]
[{title Brassed Off}]
[{title Face/Off}]
[{title Benji: Off the Leash!}]
[{title Set It Off}]

In the above results, the characters off appear at the left side of a word in all the titles.

edgeGram

{"title": "Off Beat"}
{"title": "Off the Map"}
{"title": "Off and Running"}
{"title": "Hands off Mississippi"}
{"title": "Taking Off"}
{"title": "Noises Off..."}
{"title": "Brassed Off"}
{"title": "Face/Off"}
{"title": "Benji: Off the Leash!"}
{"title": "Set It Off"}

In the above results, the characters off appear at the left side of a word in all the titles.

edgeGram

Document{{title=Off Beat}}
Document{{title=Off the Map}}
Document{{title=Off and Running}}
Document{{title=Hands off Mississippi}}
Document{{title=Taking Off}}
Document{{title=Face/Off}}
Document{{title=Noises Off...}}
Document{{title=Brassed Off}}
Document{{title=Benji: Off the Leash!}}
Document{{title=Set It Off}}

In the above results, the characters off appear at the left side of a word in all the titles.

edgeGram

{ title: 'Off Beat' }
{ title: 'Off the Map' }
{ title: 'Off and Running' }
{ title: 'Hands off Mississippi' }
{ title: 'Taking Off' }
{ title: 'Noises Off...' }
{ title: 'Brassed Off' }
{ title: 'Face/Off' }
{ title: 'Benji: Off the Leash!' }
{ title: 'Set It Off' }

In the above results, the characters off appear at the left side of a word in all the titles.

edgeGram

{'title': 'Off Beat'}
{'title': 'Off the Map'}
{'title': 'Off and Running'}
{'title': 'Hands off Mississippi'}
{'title': 'Taking Off'}
{'title': 'Noises Off...'}
{'title': 'Brassed Off'}
{'title': 'Face/Off'}
{'title': 'Benji: Off the Leash!'}
{'title': 'Set It Off'}

In the above results, the characters off appear at the left side of a word in all the titles.

Fuzzy Example

Basic Example

The following query searches for movies with the characters pre in the title field. The query uses:

Field Description
maxEdits Indicates that only one character variation is allowed in the query string pre to match the query to a word in the documents.
prefixLength Indicates that the first character in the query string pre can't change when matching the query to a word in the documents.
maxExpansions Indicates that up to two hundred and fifty six similar terms for pre can be considered when matching the query string to a word in the documents.

Copy and paste the following query into the Query Editor, and then click the Search button in the Query Editor.

[
  {
    $search: {
      autocomplete: {
        path: "title",
        query: "pre",
        fuzzy: {
          maxEdits: 1,
          prefixLength: 1,
          maxExpansions: 256
        }
      }
    }
  }
]
db.movies.aggregate([
  {
    $search: {
      "autocomplete": {
        "path": "title",
        "query": "pre",
        "fuzzy": {
          "maxEdits": 1,
          "prefixLength": 1,
          "maxExpansions": 256
        }
      }
    }
  },
  {
    $limit: 10
  },
  {
    $project: {
      "_id": 0,
      "title": 1
    }
  }
])

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 `{
“autocomplete”: {
“query”: “pre”,
“path”: “title”,
“fuzzy”: {
“maxEdits”: 1,
“prefixLength”: 1,
“maxExpansions”: 256
}
}
}`
$limit 10
$project `{
“_id”: 0,
“title”: 1,
}`
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using MongoDB.Driver.Search;

public class AutocompleteFuzzyExample
{
    private const string MongoConnectionString = "<connection-string>";

    public static void Main(string[] args)
    {
        // allow automapping of the camelCase database fields to our MovieDocument
        var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
        ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);

        // connect to your Atlas cluster
        var mongoClient = new MongoClient(MongoConnectionString);
        var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
        var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");

        // define fuzzy options
        SearchFuzzyOptions fuzzyOptions = new SearchFuzzyOptions()
            {
                MaxEdits = 1,
                PrefixLength = 1,
                MaxExpansions = 256
            };

        // define and run pipeline
        var results = moviesCollection.Aggregate()
            .Search(Builders<MovieDocument>.Search.Autocomplete(movie => movie.Title, "pre", fuzzy: fuzzyOptions))
            .Project<MovieDocument>(Builders<MovieDocument>.Projection
                .Include(movie => movie.Title)
                .Exclude(movie => movie.Id))
            .Limit(10)
            .ToList();

        // print results
        foreach (var movie in results)
        {
            Console.WriteLine(movie.ToJson());
        }
    }
}

[BsonIgnoreExtraElements]
public class MovieDocument
{
    [BsonIgnoreIfDefault]
    public ObjectId Id { get; set; }
    public string Title { get; set; }
}

package main

import (
    "context"
    "fmt"

    "go.mongodb.org/mongo-driver/v2/bson"
    "go.mongodb.org/mongo-driver/v2/mongo"
    "go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
    // connect to your Atlas cluster
    client, err := mongo.Connect(options.Client().ApplyURI("<connection-string>"))
    if err != nil {
        panic(err)
    }
    defer client.Disconnect(context.TODO())

    // set namespace
    collection := client.Database("sample_mflix").Collection("movies")

    // define pipeline stages
    searchStage := bson.D{{Key: "$search", Value: bson.D{{Key: "autocomplete", Value: bson.D{{Key: "query", Value: "pre"}, {Key: "path", Value: "title"}, {Key: "fuzzy", Value: bson.D{{Key: "maxEdits", Value: 1}, {Key: "prefixLength", Value: 1}, {Key: "maxExpansions", Value: 256}}}}}}}}
    limitStage := bson.D{{Key: "$limit", Value: 10}}
    projectStage := bson.D{{Key: "$project", Value: bson.D{{Key: "title", Value: 1}, {Key: "_id", Value: 0}}}}
    // run pipeline
    cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
    if err != nil {
        panic(err)
    }

    // print results
    var results []bson.D
    if err = cursor.All(context.TODO(), &results); err != nil {
        panic(err)
    }
    for _, result := range results {
        fmt.Println(result)
    }
}

import static com.mongodb.client.model.Aggregates.limit;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Projections.excludeId;
import static com.mongodb.client.model.Projections.fields;
import static com.mongodb.client.model.Projections.include;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;

public class AutocompleteFuzzyExample {
    public static void main(String[] args) {
        // connect to your Atlas cluster
        String uri = "<connection-string>";

        try (MongoClient mongoClient = MongoClients.create(uri)) {
            // set namespace
            MongoDatabase database = mongoClient.getDatabase("sample_mflix");
            MongoCollection<Document> collection = database.getCollection("movies");

            // define pipeline
            Document agg = new Document("$search", new Document("autocomplete",
                new Document("query", "pre")
                .append("path", "title")
                .append("fuzzy", new Document("maxEdits", 1).append("prefixLength", 1).append("maxExpansions", 256))));
            // run pipeline and print results
            collection.aggregate(Arrays.asList(agg,
                limit(10),
                project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson()));
        }
    }
}

import com.mongodb.client.model.Aggregates.limit
import com.mongodb.client.model.Aggregates.project
import com.mongodb.client.model.Projections.*
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import org.bson.Document

fun main() {
    val uri = "<connection-string>"
    val mongoClient = MongoClient.create(uri)
    val database = mongoClient.getDatabase("sample_mflix")
    val collection = database.getCollection<Document>("movies")

    runBlocking {
        val agg = Document(
            "\$search",
            Document("autocomplete", Document("query", "pre")
                .append("path", "title")
                .append("fuzzy", Document("maxEdits", 1)
                    .append("prefixLength", 1)
                    .append("maxExpansions", 256))
            )
        )

        val resultsFlow = collection.aggregate<Document>(
            listOf(
                agg,
                limit(10),
                project(fields(excludeId(), include("title")))
            )
        )
        resultsFlow.collect { println(it) }
    }
    mongoClient.close()
}
const { MongoClient } = require("mongodb");

// connect to your Atlas cluster
const uri =
    "<connection-string>";

const client = new MongoClient(uri);

async function run() {
    try {
        await client.connect();

        // set namespace
        const database = client.db("sample_mflix");
        const coll = database.collection("movies");

        // define pipeline
        const agg = [
            {$search: {autocomplete: {query: "pre", path: "title", fuzzy: {"maxEdits": 1, "prefixLength": 1, "maxExpansions": 256}}}},
            {$limit: 10},
            {$project: {_id: 0,title: 1}}
        ];
        // run pipeline
        const result = await coll.aggregate(agg);

        // print results
        await result.forEach((doc) => console.log(doc));
    } finally {
        await client.close();
    }
}
run().catch(console.dir);

import pymongo

## connect to your Atlas cluster
client = pymongo.MongoClient('<connection-string>')

## define pipeline
pipeline = [
    {"$search": {"autocomplete": {"query": "pre", "path": "title", "fuzzy": {"maxEdits": 1, "prefixLength": 1, "maxExpansions": 256}}}},
    {"$limit": 10},
    {"$project": {"_id": 0, "title": 1}},
]
## run pipeline
result = client["sample_mflix"]["movies"].aggregate(pipeline)

## print results
for i in result:
    print(i)

Note: Your Results May Vary

MongoDB Search returns different results depending on the tokenization strategy configured in the index definition for the [autocomplete](https://www.mongodb.com/docs/search/indexes/field-types/autocomplete-type.md#std-label-bson-data-types-autocomplete type. To learn more, see [How to Index Fields for Autocompletion.](https://www.mongodb.com/docs/search/indexes/field-types/autocomplete-type.md#std-label-bson-data-types-autocomplete

edgeGram

SCORE: 1  _id:  “573a1390f29313caabcd5293”
  plot: "Young Pauline is left a lot of money when her wealthy uncle dies. Howe…"
  genres: Array
  runtime: 199
  ...
  title: "The Perils of Pauline"

SCORE: 1  _id:  “573a1391f29313caabcd9458”
  plot: "A young artist draws a face at a canvas on his easel. Suddenly the mou…"
  genres: Array
  rated: "UNRATED"
  ...
  title: "The Blood of a Poet"

SCORE: 1  _id:  “573a1392f29313caabcda09b”
  plot: "Tells how King Henry VIII came to marry five more times after his divo…"
  genres: Array
  runtime: 97
  ...
  title: "The Private Life of Henry VIII."

SCORE: 1  _id:  “573a1392f29313caabcda556”
  plot: "What do women want? Don Juan is aging. He's arrived secretly in Sevill…"
  genres: Array
  runtime: 89
  ...
  title: "The Private Life of Don Juan"

SCORE: 1  _id:  “573a1392f29313caabcdaee0”
  plot: "The story of Dr. Samuel Mudd, who was imprisoned after innocently trea…"
  genres: Array
  runtime: 96
  ...
  title: "The Prisoner of Shark Island"

SCORE: 1  _id:  “573a1392f29313caabcdb3f2”
  plot: "Two lookalike boys, one a poor street kid and the other a prince, exch…"
  genres: Array
  runtime: 118
  ...
  title: "The Prince and the Pauper"

SCORE: 1  _id:  “573a1392f29313caabcdb3f4”
  plot: "An Englishman on a Ruritarian holiday must impersonate the king when t…"
  genres: Array
  runtime: 101
  ...
  title: "The Prisoner of Zenda"

SCORE: 1  _id:  “573a1392f29313caabcdb505”
  plot: "After the death of her husband, Christine realizes she has possibly wa…"
  genres: Array
  runtime: 144
  ...
  title: "Dance Program"

SCORE: 1  _id:  “573a1393f29313caabcdca58”
  plot: "While traveling in France during the Nazi invasion of 1940, an English…"
  genres: Array
  runtime: 87
  ...
  title: "The Pied Piper"

SCORE: 1  _id:  “573a1393f29313caabcdca76”
  plot: "The official World War II US Government film statement defining the va…"
  genres: Array
  runtime: 87
  ...
  title: "Prelude to War"

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.

edgeGram

{ title: 'The Perils of Pauline' },
{ title: 'The Blood of a Poet' },
{ title: 'The Private Life of Henry VIII.' },
{ title: 'The Private Life of Don Juan' },
{ title: 'The Prisoner of Shark Island' },
{ title: 'The Prince and the Pauper' },
{ title: 'The Prisoner of Zenda' },
{ title: 'Dance Program' },
{ title: 'The Pied Piper' },
{ title: 'Prelude to War' }

These results show the words that are predicted for the query string with one character modification and with the first character constant at the left side of the word in all the titles.

edgeGram

{ title: 'The Perils of Pauline' },
{ title: 'The Blood of a Poet' },
{ title: 'The Private Life of Henry VIII.' },
{ title: 'The Private Life of Don Juan' },
{ title: 'The Prisoner of Shark Island' },
{ title: 'The Prince and the Pauper' },
{ title: 'The Prisoner of Zenda' },
{ title: 'Dance Program' },
{ title: 'The Pied Piper' },
{ title: 'Prelude to War' }

These results show the words that are predicted for the query string with one character modification and with the first character constant at the left side of the word in all the titles.

edgeGram

{ "title" : "The Perils of Pauline" }
{ "title" : "The Blood of a Poet" }
{ "title" : "The Private Life of Henry VIII." }
{ "title" : "The Private Life of Don Juan" }
{ "title" : "The Prisoner of Shark Island" }
{ "title" : "The Prince and the Pauper" }
{ "title" : "The Prisoner of Zenda" }
{ "title" : "Dance Program" }
{ "title" : "The Pied Piper" }
{ "title" : "Prelude to War" }

These results show the words that are predicted for the query string with one character modification and with the first character constant at the left side of the word in all the titles.

edgeGram

[{title The Perils of Pauline}]
[{title The Blood of a Poet}]
[{title The Private Life of Henry VIII.}]
[{title The Private Life of Don Juan}]
[{title The Prisoner of Shark Island}]
[{title The Prince and the Pauper}]
[{title The Prisoner of Zenda}]
[{title Dance Program}]
[{title The Pied Piper}]
[{title Prelude to War}]

These results show the words that are predicted for the query string with one character modification and with the first character constant at the left side of the word in all the titles.

edgeGram

{"title": "The Perils of Pauline"}
{"title": "The Blood of a Poet"}
{"title": "The Private Life of Henry VIII."}
{"title": "The Private Life of Don Juan"}
{"title": "The Prisoner of Shark Island"}
{"title": "The Prince and the Pauper"}
{"title": "The Prisoner of Zenda"}
{"title": "Dance Program"}
{"title": "The Pied Piper"}
{'title': 'Prelude to War'}

These results show the words that are predicted for the query string with one character modification and with the first character constant at the left side of the word in all the titles.

edgeGram

Document{{title=The Perils of Pauline}}
Document{{title=The Private Life of Henry VIII.}}
Document{{title=Prelude to War}}
Document{{title=Sitting Pretty}}
Document{{title=The Prisoner}}
Document{{title=Chi lavora è perduto (In capo al mondo)}}
Document{{title=Profound Desires of the Gods}}
Document{{title=The Protagonists}}
Document{{title=Property Is No Longer a Theft}}
Document{{title=Premiya}}

These results show the words that are predicted for the query string with one character modification and with the first character constant at the left side of the word in all the titles.

edgeGram

{ title: 'The Perils of Pauline' }
{ title: 'The Blood of a Poet' }
{ title: 'The Private Life of Henry VIII.' }
{ title: 'The Private Life of Don Juan' }
{ title: 'The Prisoner of Shark Island' }
{ title: 'The Prince and the Pauper' }
{ title: 'The Prisoner of Zenda' }
{ title: 'Dance Program' }
{ title: 'The Pied Piper' }
{ title: 'Prelude to War' }

These results show the words that are predicted for the query string with one character modification and with the first character constant at the left side of the word in all the titles.

edgeGram

{'title': 'The Perils of Pauline'}
{'title': 'The Blood of a Poet'}
{'title': 'The Private Life of Henry VIII.'}
{'title': 'The Private Life of Don Juan'}
{'title': 'The Prisoner of Shark Island'}
{'title': 'The Prince and the Pauper'}
{'title': 'The Prisoner of Zenda'}
{'title': 'Dance Program'}
{'title': 'The Pied Piper'}
{'title': 'Prelude to War'}

These results show the words that are predicted for the query string with one character modification and with the first character constant at the left side of the word in all the titles.

Partial Match Example

The following queries demonstrate how to search the specified fields for a word or phrase that contains the sequence of characters that you specify with your query.

The query allows the following for m

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