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

```javascript
{
  $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.](https://www.mongodb.com/docs/search/indexes/field-types/autocomplete-type.md#std-label-bson-data-types-autocomplete) The `autocomplete` operator doesn't support the `multi` or `wildcard (*)` options in the `path` parameter. It also doesn't support an array of fields as the `path` value. For an example of an `autocomplete` operator query across multiple fields, see [Search Across Multiple Fields.](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-compound) | 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.

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

```javascript
{
  "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](https://cloud.mongodb.com/go?l=https%3A%2F%2Fcloud.mongodb.com%2Fv2%2F%3Cproject%3E%23%2Fclusters%2FatlasSearch%2F%3Ccluster%3E) page displays.

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

```shell
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](https://www.mongodb.com/docs/drivers/csharp/current/), 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](https://www.mongodb.com/docs/drivers/go/current/), 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](https://www.mongodb.com/docs/drivers/java-drivers/), 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](https://www.mongodb.com/docs/drivers/kotlin-drivers/), 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](https://www.mongodb.com/docs/drivers/node/current/), 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](https://www.mongodb.com/docs/drivers/pymongo/), 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.

```javascript
[
  {
    $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`.

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

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

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

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

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

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

```python
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

```text
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

```json
{ 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

```json
{ 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

```json
{ "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

```none
[{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

```json
{"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

```none
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

```javascript
{ 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

```python
{'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.

```javascript
[
  {
    $search: {
      autocomplete: {
        path: "title",
        query: "pre",
        fuzzy: {
          maxEdits: 1,
          prefixLength: 1,
          maxExpansions: 256
        }
      }
    }
  }
]
```

```javascript
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,
}` |

```csharp
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; }
}

```

```go
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)
	}
}

```

```java
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()));
        }
    }
}

```

```kotlin
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()
}
```

```javascript
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);

```

```python
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

```javascript
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

```json
{ 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

```json
{ 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

```json
{ "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

```none
[{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

```json
{"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

```none
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

```javascript
{ 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

```python
{'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 matching the query string `new
    purchase` to a word in the field:

- Allows the words `new` and `purchase` to appear anywhere in the `plot` field.

- Allows two character variation in the query string to match the query to a word in the field, but doesn't allow the first character in the query string to change.

- Allows up to two hundred and fifty six similar terms to be considered.

```javascript
[
  {
    "$search": {
      "index": "default",
      "autocomplete": {
        "path": "plot",
        "query": "new purchase",
        "tokenOrder": "any",
        "fuzzy": {
          "maxEdits": 2,
          "prefixLength": 1,
          "maxExpansions": 256
        }
      },
      "highlight": {
          "path": "plot"
      }
    }
  }
]
```

**Output:**

```javascript
SCORE: 3  _id:  "573a13a4f29313caabd112f0"
  A divorced woman and her diabetic daughter take refuge in their newly-purchased house's safe room, when three men break-in, searching for a missing fortune.
  Matching fields: plot

SCORE: 3  _id:  "573a13d1f29313caabd8e209"
  A lonely writer develops an unlikely relationship with his newly purchased operating system that's designed to meet his every need.
  Matching fields: plot

SCORE: 2  _id:  "573a13bef29313caabd5b62d"
  Set in the near future when artificial organs can be bought on credit, it revolves around a man who struggles to make the payments on a heart he has purchased. He must
  Matching fields: plot

SCORE: 2  _id:  "573a13b3f29313caabd3c91e"
  He is "purchased" by a wealthy television producer and taken to a desolate island where he must fight to the death against nine other condemned killers from all corners of the world, with freedom going to the sole survivor.
  Matching fields: plot

SCORE: 2  _id:  "573a1398f29313caabceb931"
  A country boy becomes the head of a gang through the purchase of some lucky roses from an old lady.
  Matching fields: plot, plot

SCORE: 1  _id:  "573a13a7f29313caabd1b5ab"
  An illegal Nigerian immigrant discovers the unpalatable side of London life.
  Matching fields: plot

SCORE: 1  _id:  "573a13a7f29313caabd1b5c0"
  A young dropout falls in love with a nightclub dancer...
  Matching fields: plot

SCORE: 1  _id:  "573a13a7f29313caabd1b62f"
  In 1990, to protect his fragile mother from a fatal shock after a long coma, a young man must keep her from learning that her beloved nation of East Germany as she knew it has disappeared.
  Matching fields: plot

SCORE: 1  _id:  "573a13a7f29313caabd1b6af"
  Gadget once again has to fight his arch nemesis, Claw.
  Matching fields: plot
```

The query allows the following for matching the query string `new
    purchase` to a word in the field:

- Allows the words `new` and `purchase` to appear anywhere in the `plot` field.

- Allows two character variation in the query string to match the query to a word in the field, but doesn't allow the first character in the query string to change.

- Allows up to two hundred and fifty six similar terms to be considered.

```javascript
db.movies.aggregate([
  {
    "$search": {
      "index": "default",
      "autocomplete": {
        "path": "plot",
        "query": "new purchase",
        "tokenOrder": "any",
        "fuzzy": {
          "maxEdits": 2,
          "prefixLength": 1,
          "maxExpansions": 256
        }
      },
      "highlight": {
          "path": "plot"
      }
    }
  },
  {
    "$limit": 5
  },
  {
    "$project": {
      "_id": 0,
      "title": 1,
      "plot": 1,
      "highlights": { "$meta": "searchHighlights" }
    }
  }
])
```

**Output:**

```javascript
[
  {
    plot: "A divorced woman and her diabetic daughter take refuge in their newly-purchased house's safe room, when three men break-in, searching for a missing fortune.",
    title: 'Panic Room',
    highlights: [
      {
        score: 4.364492893218994,
        path: 'plot',
        texts: [
          {
            value: 'A divorced woman and her diabetic daughter take refuge in their ',
            type: 'text'
          },
          { value: "newly-purchased house's safe", type: 'hit' },
          {
            value: ' room, when three men break-in, searching for a missing fortune.',
            type: 'text'
          }
        ]
      }
    ]
  },
  {
    plot: "A lonely writer develops an unlikely relationship with his newly purchased operating system that's designed to meet his every need.",
    title: 'Her',
    highlights: [
      {
        score: 4.198050022125244,
        path: 'plot',
        texts: [
          {
            value: 'A lonely writer develops an unlikely relationship with his ',
            type: 'text'
          },
          { value: 'newly purchased operating system', type: 'hit' },
          {
            value: " that's designed to meet his every ",
            type: 'text'
          },
          { value: 'need', type: 'hit' },
          { value: '.', type: 'text' }
        ]
      }
    ]
  },
  {
    plot: "Set in the near future when artificial organs can be bought on credit, it revolves around a man who struggles to make the payments on a heart he has purchased. He must therefore go on the run before said ticker is repossessed.",
    title: 'Repo Men',
    highlights: [
      {
        score: 2.6448397636413574,
        path: 'plot',
        texts: [
          { value: 'Set in the ', type: 'text' },
          { value: 'near future when', type: 'hit' },
          { value: ' artificial organs can be bought on credit, it revolves around a man who struggles to make the payments on a heart he has ', type: 'text' },
          { value: 'purchased. He must', type: 'hit' }
        ]
      }
    ]
  },
  {
    plot: 'A psychologically troubled novelty supplier is nudged towards a romance with an English woman, all the while being extorted by a phone-sex line run by a crooked mattress salesman, and purchasing stunning amounts of pudding.',
    title: 'Punch-Drunk Love',
    highlights: [
      {
        score: 1.2451990842819214,
        path: 'plot',
        texts: [
          { value: 'A psychologically troubled ', type: 'text' },
          { value: 'novelty supplier is', type: 'hit' },
          { value: ' ', type: 'text' },
          { value: 'nudged towards a', type: 'hit' },
          {
            value: ' romance with an English woman, all the while being extorted by a phone-sex line run by a crooked mattress salesman, and ',
            type: 'text'
          },
          { value: 'purchasing stunning amounts', type: 'hit' },
          { value: ' of pudding.', type: 'text' }
        ]
      }
    ]
  },
  {
    plot: 'Jack Conrad is awaiting the death penalty in a corrupt Central American prison. He is "purchased" by a wealthy television producer and taken to a desolate island where he must fight to the death against nine other condemned killers from all corners of the world, with freedom going to the sole survivor.',
    title: 'The Condemned',
    highlights: [
      {
        score: 2.94378924369812,
        path: 'plot',
        texts: [
          { value: 'He is "', type: 'text' },
          { value: 'purchased" by a', type: 'hit' },
          {
            value: ' wealthy television producer and taken to a desolate island where he must fight to the death against ',
            type: 'text'
          },
          { value: 'nine other condemned', type: 'hit' },
          {
            value: ' killers from all corners of the world, with freedom going to the sole survivor.',
            type: 'text'
          }
        ]
      }
    ]
  }
]
```

The following query uses the operator to query the `plot` field of the `sample_mflix.movies` collection. 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 5 results

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

The query allows the following for matching the query string `new
    purchase` to a word in the field:

- Allows the words `new` and `purchase` to appear anywhere in the `plot` field.

- Allows two character variation in the query string to match the query to a word in the field, but doesn't allow the first character in the query string to change.

- Allows up to two hundred and fifty six similar terms to be considered.

| Pipeline Stage | Query |
| --- | --- |
| `$search` | `{
  "index": "default",
  "autocomplete": {
    "path": "plot",
    "query": "new purchase",
    "tokenOrder": "any",
    "fuzzy": {
      "maxEdits": 2,
      "prefixLength": 1,
      "maxExpansions": 256
    }
  },
  "highlight": {
    "path": "plot"
  }
}` |
| `$limit` | `5` |
| `$project` | `{
  "_id": 0,
  "title": 1,
  "plot": 1,
  "highlights": { "$meta": "searchHighlights" }
}` |

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

```javascript
[
  {
    plot: "A divorced woman and her diabetic daughter take refuge in their newly-purchased house's safe room, when three men break-in, searching for a missing fortune.",
    title: 'Panic Room',
    highlights: [
      {
        score: 4.364492893218994,
        path: 'plot',
        texts: [
          {
            value: 'A divorced woman and her diabetic daughter take refuge in their ',
            type: 'text'
          },
          { value: "newly-purchased house's safe", type: 'hit' },
          {
            value: ' room, when three men break-in, searching for a missing fortune.',
            type: 'text'
          }
        ]
      }
    ]
  },
  {
    plot: "A lonely writer develops an unlikely relationship with his newly purchased operating system that's designed to meet his every need.",
    title: 'Her',
    highlights: [
      {
        score: 4.198050022125244,
        path: 'plot',
        texts: [
          {
            value: 'A lonely writer develops an unlikely relationship with his ',
            type: 'text'
          },
          { value: 'newly purchased operating system', type: 'hit' },
          {
            value: " that's designed to meet his every ",
            type: 'text'
          },
          { value: 'need', type: 'hit' },
          { value: '.', type: 'text' }
        ]
      }
    ]
  },
  {
    plot: "Set in the near future when artificial organs can be bought on credit, it revolves around a man who struggles to make the payments on a heart he has purchased. He must therefore go on the run before said ticker is repossessed.",
    title: 'Repo Men',
    highlights: [
      {
        score: 2.6448397636413574,
        path: 'plot',
        texts: [
          { value: 'Set in the ', type: 'text' },
          { value: 'near future when', type: 'hit' },
          { value: ' artificial organs can be bought on credit, it revolves around a man who struggles to make the payments on a heart he has ', type: 'text' },
          { value: 'purchased. He must', type: 'hit' }
        ]
      }
    ]
  },
  {
    plot: 'A psychologically troubled novelty supplier is nudged towards a romance with an English woman, all the while being extorted by a phone-sex line run by a crooked mattress salesman, and purchasing stunning amounts of pudding.',
    title: 'Punch-Drunk Love',
    highlights: [
      {
        score: 1.2451990842819214,
        path: 'plot',
        texts: [
          { value: 'A psychologically troubled ', type: 'text' },
          { value: 'novelty supplier is', type: 'hit' },
          { value: ' ', type: 'text' },
          { value: 'nudged towards a', type: 'hit' },
          {
            value: ' romance with an English woman, all the while being extorted by a phone-sex line run by a crooked mattress salesman, and ',
            type: 'text'
          },
          { value: 'purchasing stunning amounts', type: 'hit' },
          { value: ' of pudding.', type: 'text' }
        ]
      }
    ]
  },
  {
    plot: 'Jack Conrad is awaiting the death penalty in a corrupt Central American prison. He is "purchased" by a wealthy television producer and taken to a desolate island where he must fight to the death against nine other condemned killers from all corners of the world, with freedom going to the sole survivor.',
    title: 'The Condemned',
    highlights: [
      {
        score: 2.94378924369812,
        path: 'plot',
        texts: [
          { value: 'He is "', type: 'text' },
          { value: 'purchased" by a', type: 'hit' },
          {
            value: ' wealthy television producer and taken to a desolate island where he must fight to the death against ',
            type: 'text'
          },
          { value: 'nine other condemned', type: 'hit' },
          {
            value: ' killers from all corners of the world, with freedom going to the sole survivor.',
            type: 'text'
          }
        ]
      }
    ]
  }
]
```

The code example performs the following tasks:

- Imports `mongodb` packages and dependencies.

- Establishes a connection to your cluster.

- Runs a query that uses:

  - [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage to look for a term

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

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

    and `plot`

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

The query allows the following for matching the query string `new
    purchase` to a word in the field:

- Allows the words `new` and `purchase` to appear anywhere in the `plot` field.

- Allows two character variation in the query string to match the query to a word in the field, but doesn't allow the first character in the query string to change.

- Allows up to two hundred and fifty six similar terms to be considered.

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

public class PartialAutocomplete 
{
    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 = 2,
                PrefixLength = 1,
                MaxExpansions = 256
            };

        // define and run pipeline
        var results = moviesCollection.Aggregate()
            .Search(Builders<MovieDocument>.Search.Autocomplete(movie => movie.Plot, "new purchase", SearchAutocompleteTokenOrder.Any, fuzzy: fuzzyOptions), new SearchHighlightOptions<MovieDocument>(movie => movie.Plot),
                indexName: "default")
            .Project<MovieDocument>(Builders<MovieDocument>.Projection
                .Include(movie => movie.Plot)
                .Include(movie => movie.Title)
                .Exclude(movie => movie.Id)
                .MetaSearchHighlights("highlights"))
            .Limit(5)
            .ToList();

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

[BsonIgnoreExtraElements]
public class MovieDocument {
    [BsonIgnoreIfDefault]
    public ObjectId Id { get; set; }
    public string Plot { get; set; }
    public string Title { get; set; }
    [BsonElement("highlights")]
    public List<SearchHighlight> Highlights { get; set; }
}
```

The following query uses the operator to query the `plot` field of the `sample_mflix.movies` collection. 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 5 results

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

The query allows the following for matching the query string `new
    purchase` to a word in the field:

- Allows the words `new` and `purchase` to appear anywhere in the `plot` field.

- Allows two character variation in the query string to match the query to a word in the field, but doesn't allow the first character in the query string to change.

- Allows up to two hundred and fifty six similar terms to be considered.

```go
package main

import (
	"context"
	"fmt"
	"time"

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

// define structure of movies collection
type Movie struct {
	title string
	plot  string
}

func main() {
	var err error
	// connect to the Atlas cluster
	ctx := context.Background()
	client, err := mongo.Connect(options.Client().SetTimeout(5 * time.Second).ApplyURI("<connection-string>"))
	if err != nil {
		panic(err)
	}
	defer client.Disconnect(ctx)
	// set namespace
	collection := client.Database("sample_mflix").Collection("movies")
	// define pipeline
	searchStage := bson.D{{Key: "$search", Value: bson.M{
		"index": "default",
		"autocomplete": bson.M{
			"path": "plot", "query": "new purchase", "tokenOrder": "any", "fuzzy": bson.M{
				"maxEdits": 2, "prefixLength": 1, "maxExpansions": 256},
		},
		"highlight": bson.D{
			{Key: "path", Value: "plot"},
		},
	}}}
	limitStage := bson.D{{Key: "$limit", Value: 5}}
	projectStage := bson.D{{Key: "$project", Value: bson.D{{Key: "title", Value: 1}, {Key: "plot", Value: 1}, {Key: "_id", Value: 0}, {Key: "highlights", Value: bson.D{{Key: "$meta", Value: "searchHighlights"}}}}}}
	// run pipeline
	cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage})
	if err != nil {
		panic(err)
	}
	// print results
	var results []Movie
	if err = cursor.All(context.TODO(), &results); err != nil {
		panic(err)
	}
	for _, result := range results {
		fmt.Println(result)
	}
}
```

The code example performs the following tasks:

- Imports `mongodb` packages and dependencies.

- Establishes a connection to your cluster.

- Runs a query that uses:

  - [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage to look for a term

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

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

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

The query allows the following for matching the query string `new
    purchase` to a word in the field:

- Allows the words `new` and `purchase` to appear anywhere in the `plot` field.

- Allows two character variation in the query string to match the query to a word in the field, but doesn't allow the first character in the query string to change.

- Allows up to two hundred and fifty six similar terms to be considered.

```java
import java.util.Arrays;
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;

public class PartialMatchQuery {
	public static void main( String[] args ) {

        // define query
		Document agg = new Document("$search",
		new Document ("index", "default")
		.append("autocomplete", 
			new Document("path", "plot")
				.append("query", "new purchase")
				.append("tokenOrder", "any")
				.append("fuzzy", 
				new Document("maxEdits", 2)
					.append("prefixLength", 1)
					.append("maxExpansions", 256))));

		// specify connection
		String uri = "<connection-string>";

        // establish connection and set namespace
		try (MongoClient mongoClient = MongoClients.create(uri)) {
			MongoDatabase database = mongoClient.getDatabase("sample_mflix");
			MongoCollection<Document> collection = database.getCollection("movies");
			// run query and print results
			collection.aggregate(Arrays.asList(agg, 
				limit(5), 
				project(fields(excludeId(), include("title", "plot")))))
            .forEach(doc -> System.out.println(doc.toJson()));	
		}
	}
}
```

The code example performs the following tasks:

- Imports `mongodb` packages and dependencies.

- Establishes a connection to your cluster.

- Runs a query that uses:

  - [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage to look for a term

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

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

- Prints the documents that match the query from the `AggregateFlow` instance.

The query allows the following for matching the query string `new
    purchase` to a word in the field:

- Allows the words `new` and `purchase` to appear anywhere in the `plot` field.

- Allows two character variation in the query string to match the query to a word in the field, but doesn't allow the first character in the query string to change.

- Allows up to two hundred and fifty six similar terms to be considered.

```kotlin
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() {
    // establish connection and set namespace
    val uri = "<connection-string>"
    val mongoClient = MongoClient.create(uri)
    val database = mongoClient.getDatabase("sample_mflix")
    val collection = database.getCollection<Document>("movies")

    runBlocking {
        // define query
        val agg = Document(
            "\$search",
            Document("index", "default")
                .append(
                    "autocomplete",
                    Document("path", "plot")
                        .append("query", "new purchase")
                        .append("tokenOrder", "any")
                        .append(
                            "fuzzy",
                            Document("maxEdits", 2)
                                .append("prefixLength", 1)
                                .append("maxExpansions", 256)
                        )
                )
        )

        // run query and print results
        val resultsFlow = collection.aggregate<Document>(
            listOf(
                agg,
                limit(5),
                project(fields(excludeId(), include("title", "plot")))
            )
        )
        resultsFlow.collect { println(it) }
    }
    mongoClient.close()
}
```

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

- Runs a query that uses:

  - [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage to look for a term

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

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

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

The query allows the following for matching the query string `new
    purchase` to a word in the field:

- Allows the words `new` and `purchase` to appear anywhere in the `plot` field.

- Allows two character variation in the query string to match the query to a word in the field, but doesn't allow the first character in the query string to change.

- Allows up to two hundred and fifty six similar terms to be considered.

```javascript
const MongoClient = require("mongodb").MongoClient;
const assert = require("assert");

const agg = [
  {
    '$search': {
      'index': 'default',
      'autocomplete': {
        'path': 'plot',
        'query': 'new purchase',
        'tokenOrder': 'any',
        'fuzzy': {
          'maxEdits': 2,
          'prefixLength': 1,
          'maxExpansions': 256
        }
      },
      'highlight': {
        'path': 'plot'
      }
    }
  }, {
    '$limit': 5
  }, {
    '$project': {
      '_id': 0,
      'title': 1,
      'plot': 1,
      'highlights': {
        '$meta': 'searchHighlights'
      }
    }
  }
];

MongoClient.connect(
  "<connection-string>",
  async function (connectErr, client) {
    assert.equal(null, connectErr);
    const coll = client.db("sample_mflix").collection("movies");
    let cursor = await coll.aggregate(agg);
    await cursor.forEach((doc) => console.log(doc));
    client.close();
  }
);
```

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 (Domain Name System) seed list connection string.

- Creates an instance of the `MongoClient` class to establish a connection to your cluster.

- Runs a query that uses:

  - [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage to look for a term

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

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

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

The query allows the following for matching the query string `new
    purchase` to a word in the field:

- Allows the words `new` and `purchase` to appear anywhere in the `plot` field.

- Allows two character variation in the query string to match the query to a word in the field, but doesn't allow the first character in the query string to change.

- Allows up to two hundred and fifty six similar terms to be considered.

```python
import pymongo
import dns

client = pymongo.MongoClient('<connection-string>')
result = client['sample_mflix']['movies'].aggregate([
  {
    '$search': {
      'index': 'default',
      'autocomplete': {
        'path': 'plot',
        'query': 'new purchase',
        'tokenOrder': 'any',
        'fuzzy': {
          'maxEdits': 2,
          'prefixLength': 1,
          'maxExpansions': 256
        }
      },
      'highlight': {
        'path': 'plot'
      }
    }
  }, {
    '$limit': 5
  }, {
    '$project': {
      '_id': 0,
      'title': 1,
      'plot': 1,
      'highlights': {
        '$meta': 'searchHighlights'
      }
    }
  }
])

for i in result:
  print(i)
```

### Token Order Example

The following queries search for movies with the characters `men
    with` in the `title` field. The queries also use the `tokenOrder` field, which specifies whether the query searches for tokens in `any` order or in `sequential` order.

#### Starts With Example

You can search the `title` field for movie titles that start with a term or phrase by indexing the field using the [keyword analyzer.](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer)

You must index the field using the [keyword analyzer](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) with the `edgeGram` tokenization strategy to retrieve results for the following sample query. If you index the field using any other [built-in analyzers](https://www.mongodb.com/docs/search/indexes/analyzers/overview.md#std-label-ref-built-in-analyzers), MongoDB Search doesn't return any results because it doesn't index your text field as a single term. The `edgeGram` tokenization strategy creates tokens starting at the left side of the words.

You must also set `foldDiacritics` to `true` to return case-agnostic results. If you set `foldDiacritics` to `false`, the letter case of the query term must exactly match the letter case in the document for MongoDB Search to return any results.

```json
{
  "mappings": {
    "dynamic": false,
    "fields": {
      "title": [
      {
        "type": "token"
      },
      {
         "type": "string"
      },
      {
        "foldDiacritics": true,
        "maxGrams": 7,
        "minGrams": 3,
        "analyzer": "lucene.keyword",
        "tokenization": "edgeGram",
        "type": "autocomplete"
      }]
    }
  }
}
```

The following query searches for movie titles that start with the term `Fast &`.

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

```json
[
  {
    $search: {
      autocomplete: {
        path: "title",
        query: "Fast &",
        tokenOrder: "sequential"
      }
    }
  }
]
```

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

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

```js
db.movies.aggregate([
  {
    $search: {
      "autocomplete": {
        "query": "Fast &",
        "path": "title",
        "tokenOrder": "sequential" 
      }
    }
  },
  {
    $project: {
      "_id": 0,
      "title": 1
    }
  },
  {
    $limit: 4
  }
])
  
```

Each 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 4 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": "Fast &",
    "path": "title",
    "tokenOrder": "sequential"
  }
}` |
| `$limit` | `4` |
| `$project` | `{
  "_id": 0,
  "title": 1,
}` |

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

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

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

public class AutocompleteTokenOrderSequentialStartsWithExample
{
    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, "Fast &", SearchAutocompleteTokenOrder.Sequential))
            .Project<MovieDocument>(Builders<MovieDocument>.Projection
                .Include(movie => movie.Title)
                .Exclude(movie => movie.Id))
            .Limit(4)
            .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; }
}

```

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

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

```go
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: "Fast &"}, {Key: "path", Value: "title"}, {Key: "tokenOrder", Value: "sequential"}}}}}}
	limitStage := bson.D{{Key: "$limit", Value: 4}}
	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)
	}
}

```

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

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

```java
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 AutocompleteStartsWith {
    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", "Fast &").append("path", "title").append("tokenOrder", "sequential")));
            // run pipeline and print results
            collection.aggregate(Arrays.asList(agg,
                limit(4),
                project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson()));
        }
    }
}

```

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

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

```kotlin
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", "Fast &")
                    .append("path", "title")
                    .append("tokenOrder", "sequential")
            )
        )

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

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

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

```js
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: "Fast &", path: "title", tokenOrder: "sequential"}}},
            {$limit: 4},
            {$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);

```

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

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

```python
import pymongo

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

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

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

```

```text
SCORE: 10.042893409729004  _id:  “573a13bdf29313caabd5929f”
  fullplot: "Heading back to the streets where it all began, two men rejoin two wom…"
  imdb: Object
  year: 2009
  ...
  title: "Fast & Furious"

SCORE: 9.515419006347656  _id:  “573a13d3f29313caabd95cc5”
  fullplot: "Since Dom (Diesel) and Brian's (Walker) Rio heist toppled a kingpin's …"
  imdb: Object
  year: 2013
  ...
  title "Fast & Furious 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.

```json
{ title: 'Fast & Furious' },
{ title: 'Fast & Furious 6' }
```

```json
{ title: 'Fast & Furious' },
{ title: 'Fast & Furious 6' }
```

```json
{ "title" : "Fast & Furious" }
{ "title" : "Fast & Furious 6" }
```

```none
 [{title Fast & Furious}]
 [{title Fast & Furious 6}]
```

```json
{"title": "Fast & Furious"}
{"title": "Fast & Furious 6"}
```

```none
Document{{title=Fast & Furious}}
Document{{title=Fast & Furious 6}}
```

```javascript
{ title: 'Fast & Furious' }
{ title: 'Fast & Furious 6' }
```

```python
{'title': 'Fast & Furious'}
{'title': 'Fast & Furious 6'}
```

#### Simple `any` Example

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

```json
[
  {
    $search: {
      autocomplete: {
        path: "title",
        query: "men with",
        tokenOrder: "any"
      }
    }
  }
]
```

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

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

```js
db.movies.aggregate([
  {
    $search: {
      "autocomplete": {
      "path": "title",
      "query": "men with",
        "tokenOrder": "any"
      }
    }
  },
  {
    $limit: 4
  },
  {
    $project: {
      "_id": 0,
      "title": 1
    }
  }
])

```

Each 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 4 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": "men with",
    "path": "title",
    "tokenOrder": "any"
  }
}` |
| `$limit` | `4` |
| `$project` | `{
  "_id": 0,
  "title": 1,
}` |

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

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

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

public class AutocompleteTokenOrderAnyExample
{
    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, "men with", SearchAutocompleteTokenOrder.Any))
            .Project<MovieDocument>(Builders<MovieDocument>.Projection
                .Include(movie => movie.Title)
                .Exclude(movie => movie.Id))
            .Limit(4)
            .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; }
}

```

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

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

```go
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: "men with"}, {Key: "path", Value: "title"}, {Key: "tokenOrder", Value: "any"}}}}}}
	limitStage := bson.D{{Key: "$limit", Value: 4}}
	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)
	}
}

```

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

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

```java
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 AutocompleteTokenAny {
    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", "men with").append("path", "title").append("tokenOrder", "any")));
            // run pipeline and print results
            collection.aggregate(Arrays.asList(agg,
                limit(4),
                project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson()));
        }
    }
}

```

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

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

```kotlin
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", "men with")
                .append("path", "title")
                .append("tokenOrder", "any"))
        )

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


```

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

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

```js
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: "men with", path: "title", tokenOrder: "any"}}},
            {$limit: 4},
            {$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);

```

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

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

```python
import pymongo

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

# define pipeline
pipeline = [
    {"$search": {"autocomplete": {"query": "men with", "path": "title", "tokenOrder": "any"}}},
    {"$limit": 4},
    {"$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

```text
SCORE: 21.18158721923828  _id:  “573a139af29313caabcf0b12”
  plot: "Humberto Fuentes is a wealthy doctor whose wife has recently died. In …"
  genres: Array
  runtime: 127
  ...
  title: "Men with Guns"

SCORE: 21.18158721923828  _id:  “573a13a4f29313caabd1287f”
  plot: "Paul Gross stars as the leader of a recently reunited curling team fro…"
  genres: Array
  runtime: 102
  ...
  title: "Men with Brooms"

SCORE: 19.015962600708008  _id:  “573a1391f29313caabcd93a3”
  plot: "Navy divers clear the torpedo tube of a sunken submarine."
  genres: Array
  runtime: 77
  ...
  title: "Men Without Women"

SCORE: 11.215812683105469  _id:  “573a13b8f29313caabd4bcbf”
  plot: "A graduate student (Nicholson) copes with a recent breakup by conducti…"
  genres: Array
  runtime: 80
  ...
  title: "Brief Interviews with Hideous Men"

SCORE: 10.668076515197754  _id:  “573a13c9f29313caabd7ba99”
  plot: "The women of a remote Latin American town are forced to pick up the pi…""
  genres: Array
  runtime: 87
  ...
  title: "Without Men"

SCORE: 10.106664657592773  _id:  “573a13c8f29313caabd77ab6”
  plot: "Against the tumultuous backdrop of Iran's 1953 CIA-backed coup d'ètat,…"
  genres: Array
  runtime: 95
  ...
  title: "Women Without Men"

SCORE: 7.458737373352051  _id:  “573a1398f29313caabce9a19”
  plot: "A man's wife leaves him to take up with an artist, so the man responds…"
  genres: Array
  runtime: 99
  ...
  title: "Men..."

SCORE: 7.405402183532715  _id:  “573a13f2f29313caabdde0b4”
  plot: "Men and Chicken is a black comedy about two outcast brothers, who by g…"
  genres: Array
  runtime: 104
  ...
  title: "Men & Chicken"

SCORE: 7.2005205154418945  _id:  “573a1394f29313caabce06c3”
  plot: "During the Korean War, a battle worn Lt. and his platoon behind enemy …"
  genres: Array
  runtime: 102
  ...
  title: "Men in War"

SCORE: 7.2005205154418945  _id:  “573a1399f29313caabcec167”
  plot: "A mother of two sons finds life considerably difficult on her own afte…"
  genres: Array
  runtime: 115
  ...
  title: "Men Don't Leave"
```

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

```json
{ title: 'Men with Guns' }
{ title: 'Men with Brooms' }
{ title: 'Men Without Women' }
{ title: 'Brief Interviews with Hideous Men' }
```

### edgeGram

```json
{ title: 'Men with Guns' }
{ title: 'Men with Brooms' }
{ title: 'Men Without Women' }
{ title: 'Brief Interviews with Hideous Men' }
```

### edgeGram

```json
{ "title" : "Men with Guns" }
{ "title" : "Men with Brooms" }
{ "title" : "Men Without Women" }
{ "title" : "Brief Interviews with Hideous Men" }
```

### edgeGram

```none
[{title Men with Guns}]
[{title Men with Brooms}]
[{title Men Without Women}]
[{title Brief Interviews with Hideous Men}]
```

### edgeGram

```json
{"title": "Men with Guns"}
{"title": "Men with Brooms"}
{"title": "Men Without Women"}
{"title": "Brief Interviews with Hideous Men"}
```

### edgeGram

```none
Document{{title=Men with Brooms}}
Document{{title=Men with Guns}}
Document{{title=Men Without Women}}
Document{{title=Brief Interviews with Hideous Men}}
```

### edgeGram

```javascript
{ title: 'Men with Guns' }
{ title: 'Men with Brooms' }
{ title: 'Men Without Women' }
{ title: 'Brief Interviews with Hideous Men' }
```

### edgeGram

```python
{'title': 'Men with Guns'}
{'title': 'Men with Brooms'}
{'title': 'Men Without Women'}
{'title': 'Brief Interviews with Hideous Men'}
```

#### Simple `sequential` Example

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

```json
[
  {
    $search: {
      autocomplete: {
        path: "title",
        query: "men with",
        tokenOrder: "sequential"
      }
    }
  }
]
```

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

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

```js
db.movies.aggregate([
  {
    $search: {
      "autocomplete": {
        "path": "title",
        "query": "men with",
        "tokenOrder": "sequential"
      }
    }
  },
  {
    $limit: 4
  },
  {
    $project: {
      "_id": 0,
      "title": 1
    }
  }
])

```

Each 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 4 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": "men with",
    "path": "title",
    "tokenOrder": "sequential"
  }
}` |
| `$limit` | `4` |
| `$project` | `{
  "_id": 0,
  "title": 1,
}` |

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

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

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

public class AutocompleteTokenOrderSequentialSimpleExample
{
    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, "men with", SearchAutocompleteTokenOrder.Sequential))
            .Project<MovieDocument>(Builders<MovieDocument>.Projection
                .Include(movie => movie.Title)
                .Exclude(movie => movie.Id))
            .Limit(4)
            .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; }
}

```

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

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

```go
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: "men with"}, {Key: "path", Value: "title"}, {Key: "tokenOrder", Value: "sequential"}}}}}}
	limitStage := bson.D{{Key: "$limit", Value: 4}}
	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)
	}
}

```

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

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

```java
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 AutocompleteTokenSequential {
    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", "men with").append("path", "title").append("tokenOrder", "sequential")));
            // run pipeline and print results
            collection.aggregate(Arrays.asList(agg,
                limit(4),
                project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson()));
        }
    }
}

```

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

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

```kotlin
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", "men with")
                    .append("path", "title")
                    .append("tokenOrder", "sequential")
            )
        )

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

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

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

```js
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: "men with", path: "title", tokenOrder: "sequential"}}},
            {$limit: 4},
            {$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);

```

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

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

```python
import pymongo

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

# define pipeline
pipeline = [
    {"$search": {"autocomplete": {"query": "men with", "path": "title", "tokenOrder": "sequential"}}},
    {"$limit": 4},
    {"$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

```text
SCORE: 12.644559860229492  _id:  “573a139af29313caabcf0b12”
  plot: "Humberto Fuentes is a wealthy doctor whose wife has recently died. In …"
  genres: Array
  runtime: 127
  ...
  title: "Men with Guns"

SCORE: 12.644559860229492  _id:  “573a13a4f29313caabd1287f”
  plot: "Paul Gross stars as the leader of a recently reunited curling team fro…"
  genres: Array
  runtime: 102
  ...
  title: "Men with Brooms"

SCORE: 7.997925281524658  _id:  “573a1391f29313caabcd93a3”
  plot: "Navy divers clear the torpedo tube of a sunken submarine."
  genres: Array
  runtime: 77
  ...
  title: "Men Without Women"
```

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

```json
{ title: 'Men with Guns' },
{ title: 'Men with Brooms' },
{ title: 'Men Without Women' }
```

### edgeGram

```json
{ title: 'Men with Guns' },
{ title: 'Men with Brooms' },
{ title: 'Men Without Women' }
```

### edgeGram

```json
{"title": "Men with Guns"}
{"title": "Men with Brooms"}
{"title": "Men Without Women"}
```

### edgeGram

```none
[{title Men with Guns}]
[{title Men with Brooms}]
[{title Men Without Women}]
```

### edgeGram

```json
{"title": "Men with Guns"}
{"title": "Men with Brooms"}
{"title": "Men Without Women"}
```

### edgeGram

```none
Document{{title=Men with Brooms}}
Document{{title=Men with Guns}}
Document{{title=Men Without Women}}
```

### edgeGram

```javascript
{ title: 'Men with Guns' }
{ title: 'Men with Brooms' }
{ title: 'Men Without Women' }
```

### edgeGram

```python
{'title': 'Men with Guns'}
{'title': 'Men with Brooms'}
{'title': 'Men Without Women'}
```

### Highlighting Example

The following query searches for the characters `ger` in the `title` field of the `movies` collection, with the `highlight` option enabled for the `title` field.

**Important:**

To highlight the autocomplete indexed version of a path, the [autocomplete operator](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) must be the only operator that uses that path in the query.

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

```javascript
[
  {
    $search: {
      autocomplete: {
        path: "title",
        query: "ger"
      },
      highlight: {
        path: "title"
      }
    }
  }
]
```

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

- [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to:

  - return the document's score.

  - exclude all fields except `title`.

  - add a new field called `highlights`, which contains highlighting information.

```javascript
db.movies.aggregate([
  {
    $search: {
      "autocomplete": {
        "path": "title",
        "query": ["ger"]
      },
      "highlight": { 
        "path": "title"
      }
    }
  },
  {
    $limit: 5
  }, 
  { 
    $project: {
        
      "score": { $meta: "searchScore" },
      "title": 1,
      "_id": 0,
      "highlights": { "$meta": "searchHighlights" }
    }
  }
])

```

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

- [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to:

  - return the document's score.

  - exclude all fields except `title`.

  - add a new field called `highlights`, which contains highlighting information.

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": {
    "path": "title",
    "query": ["ger"]
  },
  "highlight": {
    "path": "title"
  }
}` |
| `$limit` | `5` |
| `$project` | `{
  "score": { $meta: "searchScore" },
  "title": 1,
  "_id": 0,
  "highlights": { "$meta": "searchHighlights" }
}` |

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

- [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to:

  - return the document's score.

  - exclude all fields except `title`.

  - add a new field called `highlights`, which contains highlighting information.

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

public class AutocompleteHighlightExample
{
    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, "ger"), new SearchHighlightOptions<MovieDocument>(movie => movie.Title))
            .Project<MovieDocument>(Builders<MovieDocument>.Projection
                .Include(movie => movie.Title)
                .Exclude(movie => movie.Id)
                .MetaSearchScore(movie => movie.Score)
                .MetaSearchHighlights("highlights"))
            .Limit(5)
            .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; }
    [BsonElement("highlights")]
    public List<SearchHighlight> Highlights { get; set; }
    public double Score { 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 5 results.

- [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to:

  - return the document's score.

  - exclude all fields except `title`.

  - add a new field called `highlights`, which contains highlighting information.

```go
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.M{"query": "ger", "path": "title"}}, {Key: "highlight", Value: bson.D{{Key: "path", Value: "title"}}}}}}
	limitStage := bson.D{{Key: "$limit", Value: 5}}
	projectStage := bson.D{{Key: "$project", Value: bson.D{{Key: "score", Value: bson.D{{Key: "$meta", Value: "searchScore"}}}, {Key: "title", Value: 1}, {Key: "_id", Value: 0}, {Key: "highlight", Value: bson.D{{Key: "$meta", Value: "searchHighlights"}}}}}}
	// 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 5 results.

- [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to:

  - return the document's score.

  - exclude all fields except `title`.

  - add a new field called `highlights`, which contains highlighting information.

```java
import static com.mongodb.client.model.Aggregates.limit;
import static com.mongodb.client.model.Aggregates.project;
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 AutocompleteHighlight {
    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("path", "title").append("query", Arrays.asList("ger")))
                    .append("highlight", new Document("path", "title")));
            // run pipeline and print results
            collection.aggregate(Arrays.asList(agg,
                limit(5),
                project(Document.parse("{score: {$meta: 'searchScore'}, _id: 0, title: 1, highlights: {$meta: 'searchHighlights'}}"))))
                .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 5 results.

- [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to:

  - return the document's score.

  - exclude all fields except `title`.

  - add a new field called `highlights`, which contains highlighting information.

```kotlin
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("path", "title")
                .append("query", listOf("ger"))
            ).append("highlight", Document("path", "title"))
        )

        val resultsFlow = collection.aggregate<Document>(
            listOf(
                agg,
                limit(5),
                project(fields(
                    excludeId(),
                    include("title"),
                    computed("score", Document("\$meta", "searchScore")),
                    computed("highlights", Document("\$meta", "searchHighlights"))
                ))
            )
        )
        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 5 results.

- [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to:

  - return the document's score.

  - exclude all fields except `title`.

  - add a new field called `highlights`, which contains highlighting information.

```javascript
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: "ger", path: "title"}, highlight:{path: "title"}}},
            {$limit: 5},
            {$project: {score: {$meta: "searchScore"}, _id: 0,title: 1, highlights: {$meta: "searchHighlights"}}}
        ];
        // run pipeline
        const result = coll.aggregate(agg);

        // print results
        result.forEach((doc) => console.dir(JSON.stringify(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 5 results.

- [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to:

  - return the document's score.

  - exclude all fields except `title`.

  - add a new field called `highlights`, which contains highlighting information.

```python
import pymongo

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

# define pipeline
pipeline = [
    {"$search":{"autocomplete": {"query": "ger", "path": "title"}, "highlight": {"path": "title"}}},
    {"$limit": 5},
    {"$project": {"score": {"$meta": "searchScore"},"_id": 0, "title": 1, "highlights": {"$meta": "searchHighlights"}}},
]
# 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

```javascript
SCORE: 6.0822906494140625  _id:  “573a1390f29313caabcd50e5”
  Gertie the Dinosaur
  Matching fields: title

SCORE: 6.0822906494140625  _id:  “573a1393f29313caabcddae1”
  Germany Year Zero
  Matching fields: title

SCORE: 6.0822906494140625  _id:  “573a1397f29313caabce6b75”
  Germany in Autumn
  Matching fields: title

SCORE: 6.0822906494140625  _id:  “573a1397f29313caabce77b5”
  Germany Pale Mother
  Matching fields: title

SCORE: 6.0822906494140625  _id:  “573a13d4f29313caabd99fa2”
  Gerhard Richter - Painting
  Matching fields: title

SCORE: 6.018838405609131  _id:  “573a1399f29313caabcedb50”
  Geronimo: An American Legend
  Matching fields: title

SCORE: 5.825854301452637  _id:  “573a139bf29313caabcf36bd”
  Geri's Game
  Matching fields: title

SCORE: 5.777737617492676  _id:  “573a13a5f29313caabd15dae”
  How to Live in the German Federal Republic
  Matching fields: title

SCORE: 5.738928318023682  _id:  “573a13b4f29313caabd41bb7”
  The Gerson Miracle
  Matching fields: title

SCORE: 5.738928318023682  _id:  “573a13d2f29313caabd922de”
  The German Doctor
  Matching fields: title
```

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

```json
{
  title: 'Gertie the Dinosaur',
  score: 6.085907459259033,
  highlights: [{
    score: 0.9227690100669861,
    path: 'title',
    texts: [ { value: 'Gertie the Dinosaur', type: 'hit' } ]
  }]
},
{
  title: 'Germany Year Zero',
  score: 6.085907459259033,
  highlights: [{
    score: 0.9180012345314026,
    path: 'title',
    texts: [ { value: 'Germany Year Zero', type: 'hit' } ]
   }]
},
{
  title: 'Germany in Autumn',
  score: 6.085907459259033,
  highlights: [{
    score: 0.9180012345314026,
    path: 'title',
    texts: [ { value: 'Germany in Autumn', type: 'hit' } ]
  }]
},
{
  title: 'Germany Pale Mother',
  score: 6.085907459259033,
  highlights: [{
    score: 0.9227690100669861,
    path: 'title',
    texts: [ { value: 'Germany Pale Mother', type: 'hit' } ]
  }]
},
{
  title: 'Gerhard Richter - Painting',
  score: 6.085907459259033,
  highlights: [{
    score: 0.9386774897575378,
    path: 'title',
    texts: [ { value: 'Gerhard Richter - Painting', type: 'hit' } ]
  }]
}
```

MongoDB Search  returns these results because the characters `ger` appear at the left side of a word in all the titles. MongoDB Search matches a highlight `hit` more coarsely to your query terms when a highlighted path is referenced only in the autocomplete operators of the highlighted query.

### edgeGram

```json
{
  title: 'Gertie the Dinosaur',
  score: 6.085907459259033,
  highlights: [{
    score: 0.9227690100669861,
    path: 'title',
    texts: [ { value: 'Gertie the Dinosaur', type: 'hit' } ]
  }]
},
{
  title: 'Germany Year Zero',
  score: 6.085907459259033,
  highlights: [{
    score: 0.9180012345314026,
    path: 'title',
    texts: [ { value: 'Germany Year Zero', type: 'hit' } ]
   }]
},
{
  title: 'Germany in Autumn',
  score: 6.085907459259033,
  highlights: [{
    score: 0.9180012345314026,
    path: 'title',
    texts: [ { value: 'Germany in Autumn', type: 'hit' } ]
  }]
},
{
  title: 'Germany Pale Mother',
  score: 6.085907459259033,
  highlights: [{
    score: 0.9227690100669861,
    path: 'title',
    texts: [ { value: 'Germany Pale Mother', type: 'hit' } ]
  }]
},
{
  title: 'Gerhard Richter - Painting',
  score: 6.085907459259033,
  highlights: [{
    score: 0.9386774897575378,
    path: 'title',
    texts: [ { value: 'Gerhard Richter - Painting', type: 'hit' } ]
  }]
}
```

MongoDB Search  returns these results because the characters `ger` appear at the left side of a word in all the titles. MongoDB Search matches a highlight `hit` more coarsely to your query terms when a highlighted path is referenced only in the autocomplete operators of the highlighted query.

### edgeGram

```json
{ "title" : "Gertie the Dinosaur", "highlights" : [{ "path" : "title", "score" : 0.92276901006698608, "texts" : [{ "type" : "Hit", "value" : "Gertie the Dinosaur" }] }], "score" : 6.0822906494140625 }
{ "title" : "Germany Year Zero", "highlights" : [{ "path" : "title", "score" : 0.91800123453140259, "texts" : [{ "type" : "Hit", "value" : "Germany Year Zero" }] }], "score" : 6.0822906494140625 }
{ "title" : "Germany in Autumn", "highlights" : [{ "path" : "title", "score" : 0.91800123453140259, "texts" : [{ "type" : "Hit", "value" : "Germany in Autumn" }] }], "score" : 6.0822906494140625 }
{ "title" : "Germany Pale Mother", "highlights" : [{ "path" : "title", "score" : 0.92276901006698608, "texts" : [{ "type" : "Hit", "value" : "Germany Pale Mother" }] }], "score" : 6.0822906494140625 }
{ "title" : "Gerhard Richter - Painting", "highlights" : [{ "path" : "title", "score" : 0.93867748975753784, "texts" : [{ "type" : "Hit", "value" : "Gerhard Richter - Painting" }] }], "score" : 6.0822906494140625 }
```

MongoDB Search  returns these results because the characters `ger` appear at the left side of a word in all the titles. MongoDB Search matches a highlight `hit` more coarsely to your query terms when a highlighted path is referenced only in the autocomplete operators of the highlighted query.

### edgeGram

```none
[
   {title Gertie the Dinosaur}
   {score 6.085907459259033}
   {highlight [[
      {score 0.9227690100669861}
      {path title}
      {texts [[{value Gertie the Dinosaur} {type hit}]]}]]}]
[
   {title Germany Year Zero}
   {score 6.085907459259033}
   {highlight [[
      {score 0.9180012345314026}
      {path title}
      {texts [[{value Germany Year Zero} {type hit}]]}]]}]
[
   {title Germany in Autumn}
   {score 6.085907459259033}
   {highlight [[
      {score 0.9180012345314026}
      {path title}
      {texts [[{value Germany in Autumn} {type hit}]]}]]}]
[
   {title Germany Pale Mother}
   {score 6.085907459259033}
   {highlight [[
      {score 0.9227690100669861}
      {path title}
      {texts [[{value Germany Pale Mother} {type hit}]]}]]}]
[
   {title Gerhard Richter - Painting}
   {score 6.085907459259033}
   {highlight [[
      {score 0.9386774897575378}
      {path title}
      {texts [[{value Gerhard Richter - Painting} {type hit}]]}]]}]
```

MongoDB Search  returns these results because the characters `ger` appear at the left side of a word in all the titles. MongoDB Search matches a highlight `hit` more coarsely to your query terms when a highlighted path is referenced only in the autocomplete operators of the highlighted query.

### edgeGram

```json
{
  "title": "Gertie the Dinosaur",
  "score": 6.085907459259033,
  "highlights": [{
    "score": 0.9227690100669861,
    "path": "title",
    "texts": [{"value": "Gertie the Dinosaur", "type": "hit"}]}]}
{
  "title": "Germany Year Zero",
  "score": 6.085907459259033,
  "highlights": [{
    "score": 0.9180012345314026,
    "path": "title",
    "texts": [{"value": "Germany Year Zero", "type": "hit"}]}]}
{
  "title": "Germany in Autumn",
  "score": 6.085907459259033,
  "highlights": [{
    "score": 0.9180012345314026,
    "path": "title",
    "texts": [{"value": "Germany in Autumn", "type": "hit"}]}]}
{
  "title": "Germany Pale Mother",
  "score": 6.085907459259033,
  "highlights": [{
    "score": 0.9227690100669861,
    "path": "title",
    "texts": [{"value": "Germany Pale Mother", "type": "hit"}]}]}
{
  "title": "Gerhard Richter - Painting",
  "score": 6.085907459259033,
  "highlights": [{
    "score": 0.9386774897575378,
    "path": "title",
    "texts": [{"value": "Gerhard Richter - Painting", "type": "hit"}]}]}
```

MongoDB Search  returns these results because the characters `ger` appear at the left side of a word in all the titles. MongoDB Search matches a highlight `hit` more coarsely to your query terms when a highlighted path is referenced only in the autocomplete operators of the highlighted query.

### edgeGram

```none
Document{{title=Germany in Autumn, score=6.160550117492676, highlights=[Document{{score=0.9180012345314026, path=title, texts=[Document{{value=Germany in Autumn, type=hit}}]}}]}}
Document{{title=Gertie the Dinosaur, score=6.160550117492676, highlights=[Document{{score=0.9227690100669861, path=title, texts=[Document{{value=Gertie the Dinosaur, type=hit}}]}}]}}
Document{{title=Germany Pale Mother, score=6.160550117492676, highlights=[Document{{score=0.9227690100669861, path=title, texts=[Document{{value=Germany Pale Mother, type=hit}}]}}]}}
Document{{title=Geronimo: An American Legend, score=6.096138954162598, highlights=[Document{{score=0.9430088996887207, path=title, texts=[Document{{value=Geronimo: An American, type=hit}}, Document{{value= Legend, type=text}}]}}]}}
Document{{title=Geri's Game, score=5.900832176208496, highlights=[Document{{score=1.1180211305618286, path=title, texts=[Document{{value=Geri's Game, type=hit}}]}}]}}
```

MongoDB Search  returns these results because the characters `ger` appear at the left side of a word in all the titles. MongoDB Search matches a highlight `hit` more coarsely to your query terms when a highlighted path is referenced only in the autocomplete operators of the highlighted query.

### edgeGram

```javascript
'{
   "title":"Gertie the Dinosaur",
   "score":6.0822906494140625,
   "highlights":[{
     "score":0.9227690100669861,
     "path":"title",
     "texts":[{"value":"Gertie the Dinosaur","type":"hit"}]}]}'
'{
   "title":"Germany Year Zero",
   "score":6.0822906494140625,
   "highlights":[{
     "score":0.9180012345314026,
     "path":"title",
     "texts":[{"value":"Germany Year Zero","type":"hit"}]}]}'
'{
   "title":"Germany in Autumn",
   "score":6.0822906494140625,
   "highlights":[{
     "score":0.9180012345314026,
     "path":"title",
     "texts":[{"value":"Germany in Autumn","type":"hit"}]}]}'
'{
   "title":"Germany Pale Mother",
   "score":6.0822906494140625,
   "highlights":[{
     "score":0.9227690100669861,
     "path":"title",
     "texts":[{"value":"Germany Pale Mother","type":"hit"}]}]}'
'{
   "title":"Gerhard Richter - Painting",
   "score":6.0822906494140625,
   "highlights":[{
     "score":0.9386774897575378,
     "path":"title",
     "texts":[{"value":"Gerhard Richter - Painting","type":"hit"}]}]}'
```

MongoDB Search  returns these results because the characters `ger` appear at the left side of a word in all the titles. MongoDB Search matches a highlight `hit` more coarsely to your query terms when a highlighted path is referenced only in the autocomplete operators of the highlighted query.

### edgeGram

```python
{
  'highlights': [{
    'path': 'title',
    'score': 0.9227690100669861,
    'texts': [{'type': 'hit', 'value': 'Gertie the Dinosaur'}]}],
  'score': 6.085907459259033,
  'title': 'Gertie the Dinosaur'}
{
  'highlights': [{
    'path': 'title',
    'score': 0.9180012345314026,
    'texts': [{'type': 'hit', 'value': 'Germany Year Zero'}]}],
  'score': 6.085907459259033,
  'title': 'Germany Year Zero'}
{
  'highlights': [{
    'path': 'title',
    'score': 0.9180012345314026,
    'texts': [{'type': 'hit', 'value': 'Germany in Autumn'}]}],
  'score': 6.085907459259033,
  'title': 'Germany in Autumn'}
{
  'highlights': [{
    'path': 'title',
    'score': 0.9227690100669861,
    'texts': [{'type': 'hit', 'value': 'Germany Pale Mother'}]}],
  'score': 6.085907459259033,
  'title': 'Germany Pale Mother'}
{
  'highlights': [{
    'path': 'title',
    'score': 0.9386774897575378,
    'texts': [{'type': 'hit', 'value': 'Gerhard Richter - Painting'}]}],
  'score': 6.085907459259033,
  'title': 'Gerhard Richter - Painting'}
```

MongoDB Search  returns these results because the characters `ger` appear at the left side of a word in all the titles. MongoDB Search matches a highlight `hit` more coarsely to your query terms when a highlighted path is referenced only in the autocomplete operators of the highlighted query.

### Search Across Multiple Fields

The following query searches the `title` and `plot` fields of the `movies` collection for words that begin with the character string `inter` using the [compound](https://www.mongodb.com/docs/search/query/operators-collectors/compound.md#std-label-compound-ref) operator.

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

```javascript
[
  {
    $search: {
      compound: {
        should: [
          {
            autocomplete: {
              query: "inter",
              path: "title"
            }
          },
          {
            autocomplete: {
              query: "inter",
              path: "plot"
            }
          }
        ],
        minimumShouldMatch: 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` and `plot`.

```javascript
db.movies.aggregate([
  {
    $search: {
      "compound": {
        "should": [
          {
            "autocomplete": {
              "query": "inter",
              "path": "title",
            },
          },
          {
            "autocomplete": {
              "query": "inter",
              "path": "plot"
            }
          }
        ],
        "minimumShouldMatch": 1
      },
    },
  },
  {
    $limit: 10,
  },
  {
    $project: 
      {
        "_id": 0,
        "title": 1,
        "plot": 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` and `plot`.

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` | `{
  "compound": {
    "should": [{
      "autocomplete": {
        "query": "inter",
        "path": "title"
      }
    },
    {
      "autocomplete": {
        "query": "inter",
        "path": "plot"
      }
    }],
    "minimumShouldMatch": 1
  }
}` |
| `$limit` | `10` |
| `$project` | `{
  "_id": 0,
  "title": 1,
  "plot": 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` and `plot`.

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

public class AutocompleteCompoundExample
{
    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.Compound()
                .Should(Builders<MovieDocument>.Search.Autocomplete(movie => movie.Title, "inter"))
                .Should(Builders<MovieDocument>.Search.Autocomplete(movie => movie.Plot, "inter")))
            .Project<MovieDocument>(Builders<MovieDocument>.Projection
                .Include(movie => movie.Plot)
                .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 Plot { 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` and `plot`.

```go
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: "compound", Value: bson.D{
				{Key: "should", Value: bson.A{
					bson.D{
						{Key: "autocomplete", Value: bson.D{{Key: "query", Value: "inter"}, {Key: "path", Value: "title"}}},
					},
					bson.D{
						{Key: "autocomplete", Value: bson.D{{Key: "query", Value: "inter"}, {Key: "path", Value: "plot"}}},
					},
				}},
				{Key: "minimumShouldMatch", Value: 1},
			}},
		}},
	}
	limitStage := bson.D{{Key: "$limit", Value: 10}}
	projectStage := bson.D{{Key: "$project", Value: bson.D{{Key: "title", Value: 1}, {Key: "plot", 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` and `plot`.

```java
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 AutocompleteQuery {

    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(new Document("should", Arrays.asList(new Document("autocomplete", 
                                new Document("path", "title")
                                        .append("query", "inter")), 
                                new Document("autocomplete", 
                                new Document("path", "plot")
                                        .append("query", "inter"))))
                            .append("minimumShouldMatch", 1L));

            // run pipeline and print results
            collection.aggregate(Arrays.asList(
							eq("$search", eq("compound", 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` and `plot`.

```kotlin
import com.mongodb.client.model.Aggregates.limit
import com.mongodb.client.model.Aggregates.project
import com.mongodb.client.model.Filters.eq
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(
            Document(
                "should", listOf(
                    Document(
                        "autocomplete",
                        Document("path", "title")
                            .append("query", "inter")
                    ),
                    Document(
                        "autocomplete",
                        Document("path", "plot")
                            .append("query", "inter")
                    )
                )
            ).append("minimumShouldMatch", 1L)
        )

        val resultsFlow = collection.aggregate<Document>(
            listOf(
                eq("\$search", eq("compound", agg)),
                limit(10),
                project(fields(excludeId(), include("title", "plot")))
            )
        )
        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` and `plot`.

```javascript
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': {
                    'compound': {
                        'should': [
                            {
                                'autocomplete': {
                                    'query': 'inter', 
                                    'path': 'title'
                                }
                            }, 
                            {
                                'autocomplete': {
                                    'query': 'inter', 
                                    'path': 'plot'
                                }
                            }
                        ], 
                        'minimumShouldMatch': 1
                    }
                }
            }, 
            {
                '$limit': 10
            }, 
            {
                '$project': {
                    '_id': 0, 
                    'title': 1, 
                    'plot': 1
                }
            }
        ];
        // run pipelines
        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` and `plot`.

```python
import pymongo

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

# define pipeline
pipeline = [
    {
        '$search': {
            'compound': {
                'should': [
                    {
                        'autocomplete': {
                            'query': 'inter', 
                            'path': 'title'
                        }
                    }, {
                        'autocomplete': {
                            'query': 'inter', 
                            'path': 'plot'
                        }
                    }
                ], 
                'minimumShouldMatch': 1
            }
        }
    }, 
    {
        '$limit': 10
    }, 
    {
        '$project': {
            '_id': 0, 'title': 1, 'plot': 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

```javascript
 SCORE: 8.931777000427246  _id:  "573a13b8f29313caabd4bcbf"
   plot: "A graduate student (Nicholson) copes with a recent breakup by conducting interviews with various men."
   genres: Array
   awards: Object
   ...
   title: "Brief Interviews with Hideous Men"

 SCORE: 8.2173433303833  _id:  "573a13bcf29313caabd56968"
   plot: "An Interpol agent attempts to expose a high-profile financial institution's role in an international arms dealing ring."
   genres: Array
   awards: Object
   ...
   title: "The International"

 SCORE: 8.182762145996094  _id:  "573a13aaf29313caabd22bcf"
   plot: "A variety of losers in Dublin have harrowingly farcical intersecting stories of love, greed and violence."
   genres: Array
   awards: Object
   ...
   title: "Intermission"

 SCORE: 8.182762145996094  _id:  "573a1398f29313caabceb7a6"
   plot: "A hospital nurse becomes an
  imdb: Object
  awards: Object
  ...
  title: "Interdevochka"

SCORE: 8.178873062133789  _id:  "573a13b5f29313caabd452c6"
  plot: "After falling out with his editor, a fading political journalist is forced to interview America's most popular soap actress."
  genres: Array
  awards: Object
  ...
  title: "Interview"

SCORE: 8.158283233642578  _id:  "573a1398f29313caabcea77a"
  plot: "Cinecitta, the huge movie studio outside Rome, is 50 years old and Fellini is interviewed by a Japanese TV crew about the films he has made there over the years as he begins production on ..."
  imdb: Object
  awards: Object
  ...
  title: "Intervista"

SCORE: 8.040483474731445  _id:  "573a13aef29313caabd2c796"
  plot: "Political intrigue and deception unfold inside the United Nations, where a U.S. Secret Service agent is assigned to investigate an interpreter who overhears an assassination plot."
  genres: Array
  awards: Object
  ...
  title: "The Interpreter"

SCORE: 8.02893352508545  _id:  "573a13c3f29313caabd6b5c6"
  plot: "Boy Interrupted looks at the life of Evan Perry a 15-year-old boy from New York who committed suicide in 2005. The film made by his parents Dana and Hart examines how Evan's bipolar ..."
  genres: Array
  awards: Object
  ...
  title: "Boy Interrupted"

SCORE: 8.026378631591797  _id:  "573a13d9f29313caabda8982"
  plot: "Two salesmen whose careers have been torpedoed by the digital age find their way into a coveted internship at Google, where they must compete with a group of young, tech-savvy geniuses for a shot at employment."
  genres: Array
  awards: Object
  ...
  title: "The Internship"

SCORE: 8.01746654510498  _id:  "573a13e2f29313caabdbdc4d"
  plot: "Dave Skylark and producer Aaron Rapoport run the celebrity tabloid show \"Skylark Tonight.\" When they land an interview with a surprise fan, North Korean dictator Kim Jong-un, they are recruited by the CIA to turn their trip to Pyongyang into an assassination mission."
  genres: Array
  awards: Object
  ...
  title: "The Interview"
```

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

```json
[
  {
    plot: 'A graduate student (Nicholson) copes with a recent breakup by conducting interviews with various men.',
    title: 'Brief Interviews with Hideous Men'
  },
  {
    plot: "An Interpol agent attempts to expose a high-profile financial institution's role in an international arms dealing ring.",
    title: 'The International'
  },
  {
    plot: 'A variety of losers in Dublin have harrowingly farcical intersecting stories of love, greed and violence.',
    title: 'Intermission'
  },
  {
    plot: 'A hospital nurse becomes an "international girl", a prostitute who caters to foreigners with hard currency.',
    title: 'Interdevochka'
  },
  {
    plot: "After falling out with his editor, a fading political journalist is forced to interview America's most popular soap actress.",
    title: 'Interview'
  },
  {
    plot: 'Cinecitta, the huge movie studio outside Rome, is 50 years old and Fellini is interviewed by a Japanese TV crew about the films he has made there over the years as he begins production on ...',
    title: 'Intervista'
  },
  {
    plot: 'Political intrigue and deception unfold inside the United Nations, where a U.S. Secret Service agent is assigned to investigate an interpreter who overhears an assassination plot.',
    title: 'The Interpreter'
  },
  {
    plot: "Boy Interrupted looks at the life of Evan Perry a 15-year-old boy from New York who committed suicide in 2005. The film made by his parents Dana and Hart examines how Evan's bipolar ...",
    title: 'Boy Interrupted'
  },
  {
    plot: 'Two salesmen whose careers have been torpedoed by the digital age find their way into a coveted internship at Google, where they must compete with a group of young, tech-savvy geniuses for a shot at employment.',
    title: 'The Internship'
  },
  {
    plot: 'Dave Skylark and producer Aaron Rapoport run the celebrity tabloid show "Skylark Tonight." When they land an interview with a surprise fan, North Korean dictator Kim Jong-un, they are recruited by the CIA to turn their trip to Pyongyang into an assassination mission.',
    title: 'The Interview'
  }
]
```

In these results, the characters `inter` appear at the beginning of a word in the `title` or `plot` field. MongoDB Search returns results that begin with the specified query string because MongoDB Search matches the query term to the tokens that it creates for the `title` and `plot` fields starting at the left side the word.

### edgeGram

```json
[
  {
    plot: 'A graduate student (Nicholson) copes with a recent breakup by conducting interviews with various men.',
    title: 'Brief Interviews with Hideous Men'
  },
  {
    plot: "An Interpol agent attempts to expose a high-profile financial institution's role in an international arms dealing ring.",
    title: 'The International'
  },
  {
    plot: 'A variety of losers in Dublin have harrowingly farcical intersecting stories of love, greed and violence.',
    title: 'Intermission'
  },
  {
    plot: 'A hospital nurse becomes an "international girl", a prostitute who caters to foreigners with hard currency.',
    title: 'Interdevochka'
  },
  {
    plot: "After falling out with his editor, a fading political journalist is forced to interview America's most popular soap actress.",
    title: 'Interview'
  },
  {
    plot: 'Cinecitta, the huge movie studio outside Rome, is 50 years old and Fellini is interviewed by a Japanese TV crew about the films he has made there over the years as he begins production on ...',
    title: 'Intervista'
  },
  {
    plot: 'Political intrigue and deception unfold inside the United Nations, where a U.S. Secret Service agent is assigned to investigate an interpreter who overhears an assassination plot.',
    title: 'The Interpreter'
  },
  {
    plot: "Boy Interrupted looks at the life of Evan Perry a 15-year-old boy from New York who committed suicide in 2005. The film made by his parents Dana and Hart examines how Evan's bipolar ...",
    title: 'Boy Interrupted'
  },
  {
    plot: 'Two salesmen whose careers have been torpedoed by the digital age find their way into a coveted internship at Google, where they must compete with a group of young, tech-savvy geniuses for a shot at employment.',
    title: 'The Internship'
  },
  {
    plot: 'Dave Skylark and producer Aaron Rapoport run the celebrity tabloid show "Skylark Tonight." When they land an interview with a surprise fan, North Korean dictator Kim Jong-un, they are recruited by the CIA to turn their trip to Pyongyang into an assassination mission.',
    title: 'The Interview'
  }
]
```

In these results, the characters `inter` appear at the beginning of a word in the `title` or `plot` field. MongoDB Search returns results that begin with the specified query string because MongoDB Search matches the query term to the tokens that it creates for the `title` and `plot` fields starting at the left side the word.

### edgeGram

```json
{
   "plot" : 'A graduate student (Nicholson) copes with a recent breakup by conducting interviews with various men.',
   "title" : 'Brief Interviews with Hideous Men'
}
{
   "plot" : 'An Interpol agent attempts to expose a high-profile financial institution\'s role in an international arms dealing ring.',
   "title" : 'The International'
}
{
   "plot" : 'A variety of losers in Dublin have harrowingly farcical intersecting stories of love, greed and violence.',
   "title" : 'Intermission'
}
{
   "plot" : 'A hospital nurse becomes an "international girl", a prostitute who caters to foreigners with hard currency.',
   "title" : 'Interdevochka'
}
{
   "plot" : 'After falling out with his editor, a fading political journalist is forced to interview America\'s most popular soap actress.',
   "title" : 'Interview'
}
{
   "plot" : 'Cinecitta, the huge movie studio outside Rome, is 50 years old and Fellini is interviewed by a Japanese TV crew about the films he has made there over the years as he begins production on ...',
   "title" : 'Intervista'
}
{
   "plot" : 'Political intrigue and deception unfold inside the United Nations, where a U.S. Secret Service agent is assigned to investigate an interpreter who overhears an assassination plot.',
   "title" : 'The Interpreter'
}
{
   "plot" : 'Boy Interrupted looks at the life of Evan Perry a 15-year-old boy from New York who committed suicide in 2005. The film made by his parents Dana and Hart examines how Evan\'s bipolar ...',
   "title" : 'Boy Interrupted'
}
{
   "plot" : 'Two salesmen whose careers have been torpedoed by the digital age find their way into a coveted internship at Google, where they must compete with a group of young, tech-savvy geniuses for a shot at employment.',
   "title" : 'The Internship'
}
{
   "plot" : 'Dave Skylark and producer Aaron Rapoport run the celebrity tabloid show "Skylark Tonight." When they land an interview with a surprise fan, North Korean dictator Kim Jong-un, they are recruited by the CIA to turn their trip to Pyongyang into an assassination mission.',
   "title" : 'The Interview'
}
```

In these results, the characters `inter` appear at the beginning of a word in the `title` or `plot` field. MongoDB Search returns results that begin with the specified query string because MongoDB Search matches the query term to the tokens that it creates for the `title` and `plot` fields starting at the left side the word.

### edgeGram

```none
[
 {plot A graduate student (Nicholson) copes with a recent breakup by conducting interviews with various men.}
 {title Brief Interviews with Hideous Men}
]
[
 {plot An Interpol agent attempts to expose a high-profile financial institution's role in an international arms dealing ring.}
 {title The International}
]
[
 {plot A variety of losers in Dublin have harrowingly farcical intersecting stories of love, greed and violence.}
 {title Intermission}
]
[
 {plot A hospital nurse becomes an "international girl", a prostitute who caters to foreigners with hard currency.}
 {title Interdevochka}
]
[
 {plot After falling out with his editor, a fading political journalist is forced to interview America's most popular soap actress.}
 {title Interview}
]
[
 {plot Cinecitta, the huge movie studio outside Rome, is 50 years old and Fellini is interviewed by a Japanese TV crew about the films he has made there over the years as he begins production on ...}
 {title Intervista}
]
[
 {plot Political intrigue and deception unfold inside the United Nations, where a U.S. Secret Service agent is assigned to investigate an interpreter who overhears an assassination plot.}
 {title The Interpreter}
]
[
 {plot Boy Interrupted looks at the life of Evan Perry a 15-year-old boy from New York who committed suicide in 2005. The film made by his parents Dana and Hart examines how Evan's bipolar ...}
 {title Boy Interrupted}
]
[
 {plot Two salesmen whose careers have been torpedoed by the digital age find their way into a coveted internship at Google, where they must compete with a group of young, tech-savvy geniuses for a shot at employment.}
 {title The Internship}
]
[
 {plot Dave Skylark and producer Aaron Rapoport run the celebrity tabloid show "Skylark Tonight." When they land an interview with a surprise fan, North Korean dictator Kim Jong-un, they are recruited by the CIA to turn their trip to Pyongyang into an assassination mission.}
 {title The Interview}
]
```

In these results, the characters `inter` appear at the beginning of a word in the `title` or `plot` field. MongoDB Search returns results that begin with the specified query string because MongoDB Search matches the query term to the tokens that it creates for the `title` and `plot` fields starting at the left side the word.

### edgeGram

```json
{
   "plot" : "A graduate student (Nicholson) copes with a recent breakup by conducting interviews with various men.",
   "title" : "Brief Interviews with Hideous Men"
}
{
   "plot" : "An Interpol agent attempts to expose a high-profile financial institution's role in an international arms dealing ring.",
   "title" : "The International"
}
{
   "plot" : "A variety of losers in Dublin have harrowingly farcical intersecting stories of love, greed and violence.",
   "title" : "Intermission"
}
{
   "plot" : "A hospital nurse becomes an \"international girl\", a prostitute who caters to foreigners with hard currency.",
   "title" : "Interdevochka"
}
{
   "plot" : "After falling out with his editor, a fading political journalist is forced to interview America's most popular soap actress.",
   "title" : "Interview"
}
{
   "plot" : "Cinecitta, the huge movie studio outside Rome, is 50 years old and Fellini is interviewed by a Japanese TV crew about the films he has made there over the years as he begins production on ...",
   "title" : "Intervista"
}
{
   "plot" : "Political intrigue and deception unfold inside the United Nations, where a U.S. Secret Service agent is assigned to investigate an interpreter who overhears an assassination plot.",
   "title" : "The Interpreter"
}
{
   "plot" : "Boy Interrupted looks at the life of Evan Perry a 15-year-old boy from New York who committed suicide in 2005. The film made by his parents Dana and Hart examines how Evan's bipolar ...",
   "title" : "Boy Interrupted"
}
{
   "plot" : "Two salesmen whose careers have been torpedoed by the digital age find their way into a coveted internship at Google, where they must compete with a group of young, tech-savvy geniuses for a shot at employment.",
   "title" : "The Internship"
}
{
   "plot" : "Dave Skylark and producer Aaron Rapoport run the celebrity tabloid show \"Skylark Tonight.\" When they land an interview with a surprise fan, North Korean dictator Kim Jong-un, they are recruited by the CIA to turn their trip to Pyongyang into an assassination mission.",
   "title" : "The Interview"
}
```

In these results, the characters `inter` appear at the beginning of a word in the `title` or `plot` field. MongoDB Search returns results that begin with the specified query string because MongoDB Search matches the query term to the tokens that it creates for the `title` and `plot` fields starting at the left side the word.

### edgeGram

```none
Document{{plot=A graduate student (Nicholson) copes with a recent breakup by conducting interviews with various men., title=Brief Interviews with Hideous Men}}
Document{{plot=An Interpol agent attempts to expose a high-profile financial institution's role in an international arms dealing ring., title=The International}}
Document{{plot=A variety of losers in Dublin have harrowingly farcical intersecting stories of love, greed and violence., title=Intermission}}
Document{{plot=A hospital nurse becomes an "international girl", a prostitute who caters to foreigners with hard currency., title=Interdevochka}}
Document{{plot=After falling out with his editor, a fading political journalist is forced to interview America's most popular soap actress., title=Interview}}
Document{{plot=Cinecitta, the huge movie studio outside Rome, is 50 years old and Fellini is interviewed by a Japanese TV crew about the films he has made there over the years as he begins production on ..., title=Intervista}}
Document{{plot=Political intrigue and deception unfold inside the United Nations, where a U.S. Secret Service agent is assigned to investigate an interpreter who overhears an assassination plot., title=The Interpreter}}
Document{{plot=Boy Interrupted looks at the life of Evan Perry a 15-year-old boy from New York who committed suicide in 2005. The film made by his parents Dana and Hart examines how Evan's bipolar ..., title=Boy Interrupted}}
Document{{plot=Two salesmen whose careers have been torpedoed by the digital age find their way into a coveted internship at Google, where they must compete with a group of young, tech-savvy geniuses for a shot at employment., title=The Internship}}
Document{{plot=Dave Skylark and producer Aaron Rapoport run the celebrity tabloid show "Skylark Tonight." When they land an interview with a surprise fan, North Korean dictator Kim Jong-un, they are recruited by the CIA to turn their trip to Pyongyang into an assassination mission., title=The Interview}}
```

In these results, the characters `inter` appear at the beginning of a word in the `title` or `plot` field. MongoDB Search returns results that begin with the specified query string because MongoDB Search matches the query term to the tokens that it creates for the `title` and `plot` fields starting at the left side the word.

### edgeGram

```javascript
{
   "plot": "A graduate student (Nicholson) copes with a recent breakup by conducting interviews with various men.",
   "title": "Brief Interviews with Hideous Men"
}
{
   "plot": "An Interpol agent attempts to expose a high-profile financial institution's role in an international arms dealing ring.",
   "title": "The International"
}
{
   "plot": "A variety of losers in Dublin have harrowingly farcical intersecting stories of love, greed and violence.",
   "title": "Intermission"
}
{
   "plot": "A hospital nurse becomes an \"international girl\", a prostitute who caters to foreigners with hard currency.",
   "title": "Interdevochka"
}
{
   "plot": "After falling out with his editor, a fading political journalist is forced to interview America's most popular soap actress.",
   "title": "Interview"
}
{
   "plot": "Cinecitta, the huge movie studio outside Rome, is 50 years old and Fellini is interviewed by a Japanese TV crew about the films he has made there over the years as he begins production on ...",
   "title": "Intervista"
}
{
   "plot": "Political intrigue and deception unfold inside the United Nations, where a U.S. Secret Service agent is assigned to investigate an interpreter who overhears an assassination plot.",
   "title": "The Interpreter"
}
{
   "plot": "Boy Interrupted looks at the life of Evan Perry a 15-year-old boy from New York who committed suicide in 2005. The film made by his parents Dana and Hart examines how Evan's bipolar ...",
   "title": "Boy Interrupted"
}
{
   "plot": "Two salesmen whose careers have been torpedoed by the digital age find their way into a coveted internship at Google, where they must compete with a group of young, tech-savvy geniuses for a shot at employment.",
   "title": "The Internship"
}
{
   "plot": "Dave Skylark and producer Aaron Rapoport run the celebrity tabloid show \"Skylark Tonight.\" When they land an interview with a surprise fan, North Korean dictator Kim Jong-un, they are recruited by the CIA to turn their trip to Pyongyang into an assassination mission.",
   "title": "The Interview"
}
```

In these results, the characters `inter` appear at the beginning of a word in the `title` or `plot` field. MongoDB Search returns results that begin with the specified query string because MongoDB Search matches the query term to the tokens that it creates for the `title` and `plot` fields starting at the left side the word.

### edgeGram

```json
{
   "plot": "A graduate student (Nicholson) copes with a recent breakup by conducting interviews with various men.",
   "title": "Brief Interviews with Hideous Men"
}
{
   "plot": "An Interpol agent attempts to expose a high-profile financial institution's role in an international arms dealing ring.",
   "title": "The International"
}
{
   "plot": "A variety of losers in Dublin have harrowingly farcical intersecting stories of love, greed and violence.",
   "title": "Intermission"
}
{
   "plot": "A hospital nurse becomes an \"international girl\", a prostitute who caters to foreigners with hard currency.",
   "title": "Interdevochka"
}
{
   "plot": "After falling out with his editor, a fading political journalist is forced to interview America's most popular soap actress.",
   "title": "Interview"
}
{
   "plot": "Cinecitta, the huge movie studio outside Rome, is 50 years old and Fellini is interviewed by a Japanese TV crew about the films he has made there over the years as he begins production on ...",
   "title": "Intervista"
}
{
   "plot": "Political intrigue and deception unfold inside the United Nations, where a U.S. Secret Service agent is assigned to investigate an interpreter who overhears an assassination plot.",
   "title": "The Interpreter"
}
{
   "plot": "Boy Interrupted looks at the life of Evan Perry a 15-year-old boy from New York who committed suicide in 2005. The film made by his parents Dana and Hart examines how Evan's bipolar ...",
   "title": "Boy Interrupted"
}
{
   "plot": "Two salesmen whose careers have been torpedoed by the digital age find their way into a coveted internship at Google, where they must compete with a group of young, tech-savvy geniuses for a shot at employment.",
   "title": "The Internship"
}
{
   "plot": "Dave Skylark and producer Aaron Rapoport run the celebrity tabloid show \"Skylark Tonight.\" When they land an interview with a surprise fan, North Korean dictator Kim Jong-un, they are recruited by the CIA to turn their trip to Pyongyang into an assassination mission.",
   "title": "The Interview"
}
```

In these results, the characters `inter` appear at the beginning of a word in the `title` or `plot` field. MongoDB Search returns results that begin with the specified query string because MongoDB Search matches the query term to the tokens that it creates for the `title` and `plot` fields starting at the left side the word.

### Bucket Results through Facet Queries

The following query uses the [`$searchMeta`](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta) stage to return unique values of movies that contain the term `Gravity` in the `title` field of the `movies` collection. The index definition of this query limits the results returned from a [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) index, where both the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) and [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) types are on the `title` field.

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

```javascript
[
  {
    "$searchMeta": {
      "facet": {
        "operator": {
          "autocomplete": {
            "query": "Gravity",
            "path": "title"
          }
        },
        "facets": {
          "titleFacet": {
            "type": "string",
            "path": "title"
          }
        }
      }
    }
  }
]

```

The following query uses the [`$searchMeta`](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta) stage to return unique values of movies that contain the term `Gravity` in the `title` field of the `movies` collection. The index definition of this query limits the results returned from a [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) index, where both the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) and [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) types are on the `title` field.

```javascript
db.movies.aggregate([{
  $searchMeta: {
    "facet": {
      "operator": {
        "autocomplete": {
          "query": "Gravity",
          "path": "title"
        }
      },
      "facets": {
        "titleFacet": {
          "type": "string",
          "path": "title"
        }
      }
    }
  }
}])

```

The following query uses the [`$searchMeta`](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta) stage to return unique values of movies that contain the term `Gravity` in the `title` field of the `movies` collection. The index definition of this query limits the results returned from a [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) index, where both the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) and [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) types are on the `title` field.

In the Aggregations tab of the `movies` collection, configure the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage.

| Pipeline Stage | Query |
| --- | --- |
| `$searchMeta` | `{
  facet: {
    operator: {
      autocomplete: {
          path: 'title',
          query: 'Gravity'
      }
    },
    facets: {
      titleFacet: {
        type: 'string',
        path: 'title'
      }
    }
  }
}` |

The following query uses the [`$searchMeta`](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta) stage to return unique values of movies that contain the term `Gravity` in the `title` field of the `movies` collection. The index definition of this query limits the results returned from a [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) index, where both the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) and [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) types are on the `title` field.

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

public class AutocompleteFacetExample
{
    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()
            .SearchMeta(Builders<MovieDocument>.Search.Facet(
                Builders<MovieDocument>.Search.Autocomplete(movie => movie.Title, "Gravity"),
                Builders<MovieDocument>.SearchFacet.String("titleFacet", movie => movie.Title, 100)))
            .Single();

        // print results
        Console.WriteLine(results.ToJson());
    }
}

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

```

The following query uses the [`$searchMeta`](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta) stage to return unique values of movies that contain the term `Gravity` in the `title` field of the `movies` collection. The index definition of this query limits the results returned from a [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) index, where both the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) and [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) types are on the `title` field.

```go
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
	searchMetaStage := bson.D{{Key: "$searchMeta", Value: bson.M{
		"facet": bson.M{
			"operator": bson.M{
				"autocomplete": bson.M{
					"path": "title", "query": "Gravity",
				},
			},
			"facets": bson.M{
				"titleFacet": bson.M{
					"path": "title", "type": "string",
				},
			},
		},
	}}}

	// run pipeline
	cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchMetaStage})
	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 following query uses the [`$searchMeta`](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta) stage to return unique values of movies that contain the term `Gravity` in the `title` field of the `movies` collection. The index definition of this query limits the results returned from a [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) index, where both the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) and [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) types are on the `title` field.

```java
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 FacetAutocompleteExample {
    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("$searchMeta", new Document("facet", 
            new Document("operator", 
                new Document("autocomplete", 
                    new Document("path", "title")
                    .append("query", "Gravity")))
            .append("facets", 
                new Document("titleFacet", 
                    new Document("type", "string").append("path", "title"))
             )));
            // run pipeline and print results
            collection.aggregate(Arrays.asList(agg))
                .forEach(doc -> System.out.println(doc.toJson()));

        }
    }
}

```

The following query uses the [`$searchMeta`](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta) stage to return unique values of movies that contain the term `Gravity` in the `title` field of the `movies` collection. The index definition of this query limits the results returned from a [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) index, where both the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) and [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) types are on the `title` field.

```kotlin
import com.mongodb.client.model.Aggregates.limit
import com.mongodb.client.model.Aggregates.project
import com.mongodb.client.model.Filters.eq
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(
            "\$searchMeta", Document(
                "facet",
                Document(
                    "operator",
                    Document(
                        "autocomplete",
                        Document("path", "title")
                            .append("query", "Gravity")
                    )
                )
                    .append(
                        "facets",
                        Document(
                            "titleFacet",
                            Document("type", "string").append("path", "title")
                        )
                    )
            )
        )

        val resultsFlow = collection.aggregate<Document>(listOf(agg))
        resultsFlow.collect { println(it) }
    }
    mongoClient.close()
}
```

The following query uses the [`$searchMeta`](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta) stage to return unique values of movies that contain the term `Gravity` in the `title` field of the `movies` collection. The index definition of this query limits the results returned from a [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) index, where both the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) and [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) types are on the `title` field.

```javascript
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 = [{$searchMeta: {facet: {
                operator: {
                  autocomplete: {path: "title", query: "Gravity"}
                },
                facets: {
                  titleFacet: {type: "string", path: "title"}
                }}}}];
        // run pipeline
        const result = coll.aggregate(agg);

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

```

The following query uses the [`$searchMeta`](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta) stage to return unique values of movies that contain the term `Gravity` in the `title` field of the `movies` collection. The index definition of this query limits the results returned from a [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) index, where both the [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) and [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token) types are on the `title` field.

```python
import pymongo

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

# define pipeline
pipeline = [{"$searchMeta": { 
    "facet": {
        "operator": {
          "autocomplete": {"path": "title", "query": "Gravity"}
        },
        "facets": {
          "titleFacet": {"type": "string", "path": "title"}
        }}}}]
# run pipeline
result = client["sample_mflix"]["movies"].aggregate(pipeline)

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

```

```js
count: Object
  lowerBound: 5
facet: Object
  titleFacet: Object
    buckets: Array (3)
    0: Object
      _id: "Gravity"
      count: 3
    1: Object
      _id: "Defying Gravity"
      count: 1
    2: Object
      _id: "Laws of Gravity"
      count: 1
```

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.

```text
[{
   count: { lowerBound: Long("5") },
   facet: {
      titleFacet: {
      buckets: [
         { _id: 'Gravity', count: Long("3") },
         { _id: 'Defying Gravity', count: Long("1") },
         { _id: 'Laws of Gravity', count: Long("1") }
      ]
      }
   }
}]
```

```text
[{
   count: { lowerBound: Long("5") },
   facet: {
      titleFacet: {
      buckets: [
         { _id: 'Gravity', count: Long("3") },
         { _id: 'Defying Gravity', count: Long("1") },
         { _id: 'Laws of Gravity', count: Long("1") }
      ]
      }
   }
}]
```

```json
{
  "count" : {
    "lowerBound" : NumberLong(5),
    "total" : null
  },
  "facet" : {
    "titleFacet" : {
      "buckets" : [
        {
          "_id" : "Gravity",
          "count" : NumberLong(3)
        },
        {
          "_id" : "Defying Gravity",
          "count" : NumberLong(1)
        },
        {
          "_id" : "Laws of Gravity",
          "count" : NumberLong(1)
        }]
    }
  }
}
```

```none
[
  {
    count [{
      lowerBound 5}
    ]
  }
  {
    facet [{
      titleFacet [{
        buckets [
           [{_id Gravity} {count 3}]
           [{_id Defying Gravity} {count 1}]
           [{_id Laws of Gravity} {count 1}]
        ]
     }]}]
  }
]
```

```json
{
  "count": {
    "lowerBound": 5
   },
   "facet": {
     "titleFacet": {
       "buckets": [
       {
         "_id": "Gravity",
         "count": 3
       },
       {
         "_id": "Defying Gravity",
         "count": 1
       },
       {
         "_id": "Laws of Gravity",
         "count": 1
       }]
   }
  }
}
```

```none
Document{{count=Document{{lowerBound=5}},
facet=Document{{titleFacet=Document{{buckets=[Document{{_id=Gravity,
count=3}}, Document{{_id=Defying Gravity, count=1}}, Document{{_id=Laws
of Gravity, count=1}}]}}}}}}
```

```none
'{
  "count":{
    "lowerBound":5
   },
   "facet":{
     "titleFacet":{
       "buckets":[
         {
           "_id":"Gravity",
           "count":3
         },
         {
           "_id":"Defying Gravity",
           "count":1
         },
         {
           "_id":"Laws of Gravity",
           "count":1
         }
       ]
     }
   }
 }'
```

```json
{
  'count': {'lowerBound': 5},
  'facet': {
    'titleFacet': {
      'buckets': [
      {
        '_id': 'Gravity',
        'count': 3
      },
      {
        '_id': 'Defying Gravity',
        'count': 1
      },
      {
        '_id': 'Laws of Gravity',
        'count': 1
      }]
   }
  }
}
```

MongoDB Search returns documents that contain the term `Gravity` in the `title` field. The `count` field in the results indicate the number of documents in the collection with the same title. In the results, MongoDB Search found three documents in the collection with `Gravity` as its title, but MongoDB Search omitted the duplicate titles and returned only one matching document.

MongoDB Search returns documents that contain the term `Gravity` in the `title` field. The `count` field in the results indicate the number of documents in the collection with the same title. In the results, MongoDB Search found three documents in the collection with `Gravity` as its title, but MongoDB Search omitted the duplicate titles and returned only one matching document.

If you want to see the duplicate titles as shown in the results below, run the preceding [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator query without [facets](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref) and use the [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage instead. You must also use the [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to exclude all fields except `title`.

```javascript
[
  { title: 'Gravity' },
  { title: 'Gravity' },
  { title: 'Gravity' },
  { title: 'Defying Gravity' },
  { title: 'Laws of Gravity' }
]
```

MongoDB Search returns documents that contain the term `Gravity` in the `title` field. The `count` field in the results indicate the number of documents in the collection with the same title. In the results, MongoDB Search found three documents in the collection with `Gravity` as its title, but MongoDB Search omitted the duplicate titles and returned only one matching document.

If you want to see the duplicate titles as shown in the results below, run the preceding [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator query without [facets](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref) and use the [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage instead. You must also use the [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to exclude all fields except `title`.

```javascript
[
  { title: 'Gravity' },
  { title: 'Gravity' },
  { title: 'Gravity' },
  { title: 'Defying Gravity' },
  { title: 'Laws of Gravity' }
]
```

MongoDB Search returns documents that contain the term `Gravity` in the `title` field. The `count` field in the results indicate the number of documents in the collection with the same title. In the results, MongoDB Search found three documents in the collection with `Gravity` as its title, but MongoDB Search omitted the duplicate titles and returned only one matching document.

If you want to see the duplicate titles as shown in the results below, run the preceding [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator query without [facets](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref) and use the [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage instead. You must also use the [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to exclude all fields except `title`.

```javascript
{ "title" : "Gravity" }
{ "title" : "Gravity" }
{ "title" : "Gravity" }
{ "title" : "Defying Gravity" }
{ "title" : "Laws of Gravity" }
```

MongoDB Search returns documents that contain the term `Gravity` in the `title` field. The `count` field in the results indicate the number of documents in the collection with the same title. In the results, MongoDB Search found three documents in the collection with `Gravity` as its title, but MongoDB Search omitted the duplicate titles and returned only one matching document.

If you want to see the duplicate titles as shown in the results below, run the preceding [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator query without [facets](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref) and use the [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage instead. You must also use the [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to exclude all fields except `title`.

```none
[{title Gravity}],
[{title Gravity}],
[{title Gravity}],
[{title Defying Gravity}],
[{title Laws of Gravity}]
```

MongoDB Search returns documents that contain the term `Gravity` in the `title` field. The `count` field in the results indicate the number of documents in the collection with the same title. In the results, MongoDB Search found three documents in the collection with `Gravity` as its title, but MongoDB Search omitted the duplicate titles and returned only one matching document.

If you want to see the duplicate titles as shown in the results below, run the preceding [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator query without [facets](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref) and use the [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage instead. You must also use the [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to exclude all fields except `title`.

```javascript
{"title": "Gravity"}
{"title": "Gravity"}
{"title": "Gravity"}
{"title": "Defying Gravity"}
{"title": "Laws of Gravity"}
```

MongoDB Search returns documents that contain the term `Gravity` in the `title` field. The `count` field in the results indicate the number of documents in the collection with the same title. In the results, MongoDB Search found three documents in the collection with `Gravity` as its title, but MongoDB Search omitted the duplicate titles and returned only one matching document.

If you want to see the duplicate titles as shown in the results below, run the preceding [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator query without [facets](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref) and use the [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage instead. You must also use the [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to exclude all fields except `title`.

```none
Document{{title=Gravity}}
Document{{title=Gravity}}
Document{{title=Gravity}}
Document{{title=Defying Gravity}}
Document{{title=Laws of Gravity}}
```

MongoDB Search returns documents that contain the term `Gravity` in the `title` field. The `count` field in the results indicate the number of documents in the collection with the same title. In the results, MongoDB Search found three documents in the collection with `Gravity` as its title, but MongoDB Search omitted the duplicate titles and returned only one matching document.

If you want to see the duplicate titles as shown in the results below, run the preceding [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator query without [facets](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref) and use the [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage instead. You must also use the [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to exclude all fields except `title`.

```javascript
{ title: 'Gravity' }
{ title: 'Gravity' }
{ title: 'Gravity' }
{ title: 'Defying Gravity' }
{ title: 'Laws of Gravity' }
```

MongoDB Search returns documents that contain the term `Gravity` in the `title` field. The `count` field in the results indicate the number of documents in the collection with the same title. In the results, MongoDB Search found three documents in the collection with `Gravity` as its title, but MongoDB Search omitted the duplicate titles and returned only one matching document.

If you want to see the duplicate titles as shown in the results below, run the preceding [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref) operator query without [facets](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref) and use the [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage instead. You must also use the [`$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to exclude all fields except `title`.

```python
{ 'title': 'Gravity' }
{ 'title': 'Gravity' }
{ 'title': 'Gravity' }
{ 'title': 'Defying Gravity' }
{ 'title': 'Laws of Gravity' }
```

## Learn More

To learn more, see [How to Run Autocomplete and Partial Match MongoDB Search Queries.](https://www.mongodb.com/docs/search/tutorial/partial-match.md#std-label-partial-match-tutorial)
