partial-match

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: autocomplete, string, fts-vs, data-explorer, phrase, regex, wildcard, cloud, local, vib, jsonib -->

How to Run Autocomplete and Partial Match MongoDB Search Queries

This tutorial describes how to create an index on the sample_mflix.movies collection and run partial string queries against the plot field using the Atlas UI.

To return matches for partial string queries, you can use one of the following operators:

  • The [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref operator, which allows you to search the specified fields for a word or phrase that contains the sequence of characters that you specify with your query.

  • The [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref operator, which allows you to search the specified fields for documents that contain the terms in your query string at the distance you specify between the terms.

  • The [regex](https://www.mongodb.com/docs/search/query/operators-collectors/regex.md#std-label-regex-ref operator, which allows you to search the specified fields for strings using regular expression.

  • The [wildcard](https://www.mongodb.com/docs/search/query/operators-collectors/wildcard.md#std-label-wildcard-ref operator, which allows you to search the specified fields using special characters in your query to match any character.

You can also use the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator with a custom analyzer for more fine-grained control over partial matching. To learn more, see [Custom Analyzers.](https://www.mongodb.com/docs/search/indexes/analyzers/custom.md#std-label-custom-analyzers

This tutorial takes you through the following steps:

  1. Set up a MongoDB Search index on the plot field in the sample_mflix.movies collection.

  2. Run MongoDB Search query for a partial string against the plot field in the sample_mflix.movies collection using [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref, [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref, [regex](https://www.mongodb.com/docs/search/query/operators-collectors/regex.md#std-label-regex-ref, and [wildcard](https://www.mongodb.com/docs/search/query/operators-collectors/wildcard.md#std-label-wildcard-ref operators.

Before you begin, ensure that your cluster meets the following requirements.

To complete the tutorials, you must have:

  • An Atlas cluster with MongoDB version 6.0 or later or a MongoDB self-managed cluster with MongoDB version 8.2 or later.

  • The [sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data loaded into your cluster.

  • [Project Data Access Admin](https://www.mongodb.com/docs/atlas/reference/user-roles.md#mongodb-authrole-Project-Data-Access-Admin or higher access to your project to create MongoDB Search indexes.

  • Search Tester, [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh, Compass, or a supported MongoDB Driver to run queries on your cluster.

Note:

You can run MongoDB Search queries by using any driver through the [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search aggregation stage. These tutorials include examples for a selection of clients. Refer to the specific tutorial page for details.

You can also complete these tutorials with local deployments that you create with the Atlas CLI or with an on-prem deployment. To learn more, see Create a Local Atlas Deployment and [Self-Managed Deployments.](https://www.mongodb.com/docs/manual/self-managed-deployments.md#std-label-self-managed-deployments

Create the MongoDB Search Index

  1. Navigate to the MongoDB Search page for your project.

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

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

Click your cluster name.

Click the Search tab.

  1. Click Create Index.

  2. Select JSON Editor and click Next.

  3. In the Index Name field, enter partial-match-tutorial.

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

  5. Replace the default definition with the following index definition.

### autocomplete

The following index definition creates an autocomplete index on the plot field.

json { "mappings": { "fields": { "plot": { "type": "autocomplete" } } } }

  1. Click Next.

  2. Click Create Search Index.

  3. Close the You're All Set! Modal Window.

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

  1. Wait for the index to finish building.

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

Run a Case-Sensitive Partial Match Query

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

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

### Search & Vector Search

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

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

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

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

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

The Search & Vector Search page displays.

  1. Click Query in your search index.

  2. Click Edit Query to run the sample query.

  3. Copy and paste the following query into the Query editor.

### autocomplete

The following query searches for documents where the plot field contains words that begin with haw.

json { "autocomplete": { "query": "haw", "path": "plot" } }

  1. Click Search to run the query.

MongoDB Search returns the search results for documents in the movies collection.

This tutorial describes how to create an index on the sample_mflix.movies collection and run partial string queries against the plot field using MongoDB Compass.

To return matches for partial string queries, you can use one of the following operators:

  • The [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref operator, which allows you to search the specified fields for a word or phrase that contains the sequence of characters that you specify with your query.

  • The [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref operator, which allows you to search the specified fields for documents that contain the terms in your query string at the distance you specify between the terms.

  • The [regex](https://www.mongodb.com/docs/search/query/operators-collectors/regex.md#std-label-regex-ref operator, which allows you to search the specified fields for strings using regular expression.

  • The [wildcard](https://www.mongodb.com/docs/search/query/operators-collectors/wildcard.md#std-label-wildcard-ref operator, which allows you to search the specified fields using special characters in your query to match any character.

You can also use the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator with a custom analyzer for more fine-grained control over partial matching. To learn more, see [Custom Analyzers.](https://www.mongodb.com/docs/search/indexes/analyzers/custom.md#std-label-custom-analyzers

This tutorial takes you through the following steps:

  1. Set up a MongoDB Search index on the plot field in the sample_mflix.movies collection.

  2. Run MongoDB Search query for a partial string against the plot field in the sample_mflix.movies collection using [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref, [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref, [regex](https://www.mongodb.com/docs/search/query/operators-collectors/regex.md#std-label-regex-ref, and [wildcard](https://www.mongodb.com/docs/search/query/operators-collectors/wildcard.md#std-label-wildcard-ref operators.

Before you begin, ensure that your cluster meets the following requirements.

To complete the tutorials, you must have:

  • An Atlas cluster with MongoDB version 6.0 or later or a MongoDB self-managed cluster with MongoDB version 8.2 or later.

  • The [sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data loaded into your cluster.

  • [Project Data Access Admin](https://www.mongodb.com/docs/atlas/reference/user-roles.md#mongodb-authrole-Project-Data-Access-Admin or higher access to your project to create MongoDB Search indexes.

  • Search Tester, [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh, Compass, or a supported MongoDB Driver to run queries on your cluster.

Note:

You can run MongoDB Search queries by using any driver through the [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search aggregation stage. These tutorials include examples for a selection of clients. Refer to the specific tutorial page for details.

You can also complete these tutorials with local deployments that you create with the Atlas CLI or with an on-prem deployment. To learn more, see Create a Local Atlas Deployment and [Self-Managed Deployments.](https://www.mongodb.com/docs/manual/self-managed-deployments.md#std-label-self-managed-deployments

Continue Learning

To learn more about how to implement partial matches, see MongoDB Text Search: Substring Pattern Matching Including Regex and Wildcard, Use Search Instead.

Create the MongoDB Search Index

  1. Connect to your cluster in MongoDB Compass.

  2. Navigate to the sample_mflix.movies collection.

  3. Click the Search Indexes tab.

  4. Click Create Search Index.

  5. Select JSON Editor configuration method.

  6. Enter partial-match-tutorial as the index name.

  7. Replace the default definition with the following index definition.

### autocomplete

The following index definition creates an autocomplete index on the plot field.

json { "mappings": { "fields": { "plot": { "type": "autocomplete" } } } }

  1. Click Create Search Index.

  2. Wait for the index to finish building.

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

Run a Case-Sensitive Partial Match Query

  1. Click the Aggregations tab in the sample_mflix.movies collection.

  2. Click Add Stage to add an aggregation pipeline stage.

  3. Select $search from the dropdown.

  4. Copy and paste one of the following queries into the stage editor.

### autocomplete

The following query searches for documents where the plot field contains words that begin with haw.

json { "autocomplete": { "query": "haw", "path": "plot" } }

  1. Click the green Run button to execute the aggregation.

MongoDB Compass displays the search results in the pipeline results panel.

This tutorial describes how to create an index on the sample_mflix.movies collection and run partial string queries against the plot field using mongosh.

To return matches for partial string queries, you can use one of the following operators:

  • The [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref operator, which allows you to search the specified fields for a word or phrase that contains the sequence of characters that you specify with your query.

  • The [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref operator, which allows you to search the specified fields for documents that contain the terms in your query string at the distance you specify between the terms.

  • The [regex](https://www.mongodb.com/docs/search/query/operators-collectors/regex.md#std-label-regex-ref operator, which allows you to search the specified fields for strings using regular expression.

  • The [wildcard](https://www.mongodb.com/docs/search/query/operators-collectors/wildcard.md#std-label-wildcard-ref operator, which allows you to search the specified fields using special characters in your query to match any character.

You can also use the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator with a custom analyzer for more fine-grained control over partial matching. To learn more, see [Custom Analyzers.](https://www.mongodb.com/docs/search/indexes/analyzers/custom.md#std-label-custom-analyzers

This tutorial takes you through the following steps:

  1. Set up a MongoDB Search index on the plot field in the sample_mflix.movies collection.

  2. Run MongoDB Search query for a partial string against the plot field in the sample_mflix.movies collection using [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref, [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref, [regex](https://www.mongodb.com/docs/search/query/operators-collectors/regex.md#std-label-regex-ref, and [wildcard](https://www.mongodb.com/docs/search/query/operators-collectors/wildcard.md#std-label-wildcard-ref operators.

Before you begin, ensure that your cluster meets the following requirements.

To complete the tutorials, you must have:

  • An Atlas cluster with MongoDB version 6.0 or later or a MongoDB self-managed cluster with MongoDB version 8.2 or later.

  • The [sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data loaded into your cluster.

  • [Project Data Access Admin](https://www.mongodb.com/docs/atlas/reference/user-roles.md#mongodb-authrole-Project-Data-Access-Admin or higher access to your project to create MongoDB Search indexes.

  • Search Tester, [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh, Compass, or a supported MongoDB Driver to run queries on your cluster.

Note:

You can run MongoDB Search queries by using any driver through the [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search aggregation stage. These tutorials include examples for a selection of clients. Refer to the specific tutorial page for details.

You can also complete these tutorials with local deployments that you create with the Atlas CLI or with an on-prem deployment. To learn more, see Create a Local Atlas Deployment and [Self-Managed Deployments.](https://www.mongodb.com/docs/manual/self-managed-deployments.md#std-label-self-managed-deployments

Continue Learning

To learn more about how to implement partial matches, see MongoDB Text Search: Substring Pattern Matching Including Regex and Wildcard, Use Search Instead.

Create the MongoDB Search Index

Connect to the cluster using [mongosh.](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh

Open [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh in a terminal window and connect to your Atlas cluster. For detailed instructions on connecting, see [Connect via mongosh.](https://www.mongodb.com/docs/atlas/mongo-shell-connection.md#std-label-connect-mongo-shell

Switch to the sample_mflix database.

use sample_mflix

Run the [db.collection.createSearchIndex()](https://www.mongodb.com/docs/manual/reference/method/db.collection.createSearchIndex.md#mongodb-method-db.collection.createSearchIndex method to create the search index.

autocomplete

The following command creates an autocomplete index on the plot field.

db.movies.createSearchIndex(
  "partial-match-tutorial",
  {
    "mappings": {
      "fields": {
        "plot": {
          "type": "autocomplete"
        }
      }
    }
  }
)

Run a Case-Sensitive Partial Match Query

  1. Connect to your cluster using [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh.

Open [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh in a terminal window and connect to your cluster. For detailed instructions on connecting, see [Connect to a Cluster via mongosh.](https://www.mongodb.com/docs/atlas/mongo-shell-connection.md#std-label-connect-mongo-shell

  1. Use the sample_mflix database.

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

javascript use sample_mflix

  1. Run one of the following MongoDB Search queries against the movies collection.

### autocomplete

The following query searches for documents where the plot field contains words that begin with haw.

```javascript db.movies.aggregate([ { $search: { "index": "partial-match-tutorial-autocomplete", "autocomplete": { "path": "plot", "query": "off" } } } ])

```

This tutorial describes how to create an index on the sample_mflix.movies collection and run partial string queries against the plot field using the C driver.

To return matches for partial string queries, you can use one of the following operators:

  • The [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref operator, which allows you to search the specified fields for a word or phrase that contains the sequence of characters that you specify with your query.

  • The [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref operator, which allows you to search the specified fields for documents that contain the terms in your query string at the distance you specify between the terms.

  • The [regex](https://www.mongodb.com/docs/search/query/operators-collectors/regex.md#std-label-regex-ref operator, which allows you to search the specified fields for strings using regular expression.

  • The [wildcard](https://www.mongodb.com/docs/search/query/operators-collectors/wildcard.md#std-label-wildcard-ref operator, which allows you to search the specified fields using special characters in your query to match any character.

You can also use the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator with a custom analyzer for more fine-grained control over partial matching. To learn more, see [Custom Analyzers.](https://www.mongodb.com/docs/search/indexes/analyzers/custom.md#std-label-custom-analyzers

This tutorial takes you through the following steps:

  1. Set up a MongoDB Search index on the plot field in the sample_mflix.movies collection.

  2. Run MongoDB Search query for a partial string against the plot field in the sample_mflix.movies collection using [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref, [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref, [regex](https://www.mongodb.com/docs/search/query/operators-collectors/regex.md#std-label-regex-ref, and [wildcard](https://www.mongodb.com/docs/search/query/operators-collectors/wildcard.md#std-label-wildcard-ref operators.

Before you begin, ensure that your cluster meets the following requirements.

To complete the tutorials, you must have:

  • An Atlas cluster with MongoDB version 6.0 or later or a MongoDB self-managed cluster with MongoDB version 8.2 or later.

  • The [sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data loaded into your cluster.

  • [Project Data Access Admin](https://www.mongodb.com/docs/atlas/reference/user-roles.md#mongodb-authrole-Project-Data-Access-Admin or higher access to your project to create MongoDB Search indexes.

  • Search Tester, [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh, Compass, or a supported MongoDB Driver to run queries on your cluster.

Note:

You can run MongoDB Search queries by using any driver through the [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search aggregation stage. These tutorials include examples for a selection of clients. Refer to the specific tutorial page for details.

You can also complete these tutorials with local deployments that you create with the Atlas CLI or with an on-prem deployment. To learn more, see Create a Local Atlas Deployment and [Self-Managed Deployments.](https://www.mongodb.com/docs/manual/self-managed-deployments.md#std-label-self-managed-deployments

Continue Learning

To learn more about how to implement partial matches, see MongoDB Text Search: Substring Pattern Matching Including Regex and Wildcard, Use Search Instead.

Create the MongoDB Search Index

Install the MongoDB C Driver.

For installation instructions, see the MongoDB C Driver documentation.

Create the index.

autocomplete

Create a file named create_auto_complete_index.c and paste the following code:

#include <mongoc/mongoc.h>
#include <bson/bson.h>
#include <stdio.h>
#include <stdlib.h>

// MongoDB connection URI
#define MONGODB_URI "<connection-string>"

// Database and collection names
#define DATABASE_NAME "sample_mflix"
#define COLLECTION_NAME "movies"

mongoc_client_t* connect_to_mongodb(void) {
    mongoc_client_t *client;
    mongoc_uri_t *uri;
    bson_error_t error;

    // Initialize MongoDB C driver
    mongoc_init();

    // Create a MongoDB URI object
    uri = mongoc_uri_new_with_error(MONGODB_URI, &error);
    if (!uri) {
        fprintf(stderr, "Failed to parse URI: %s\n", error.message);
        return NULL;
    }

    // Create a new client instance
    client = mongoc_client_new_from_uri(uri);
    if (!client) {
        fprintf(stderr, "Failed to create MongoDB client\n");
        mongoc_uri_destroy(uri);
        return NULL;
    }

    // Configure the client for server API version
    mongoc_client_set_error_api(client, 2);

    mongoc_uri_destroy(uri);
    return client;
}

void cleanup_mongodb(mongoc_client_t *client) {
    if (client) {
        mongoc_client_destroy(client);
    }
    mongoc_cleanup();
}

int main(void) {
    mongoc_client_t *client;
    mongoc_database_t *database;
    mongoc_collection_t *collection;
    bson_t *index_spec;
    bson_error_t error;
    char *index_name;
    bool result;

    // Connect to MongoDB
    client = connect_to_mongodb();
    if (!client) {
        return EXIT_FAILURE;
    }

    printf("Connected to MongoDB Atlas\n");

    // Get database and collection
    database = mongoc_client_get_database(client, DATABASE_NAME);
    collection = mongoc_client_get_collection(client, DATABASE_NAME, COLLECTION_NAME);

    // Create the search index specification
    index_spec = bson_new();

    // Build the index definition
    bson_t *definition = bson_new();
    bson_t *mappings = bson_new();
    bson_t *fields = bson_new();
    bson_t *title_field = bson_new();

    // Configure title field for autocomplete
    BSON_APPEND_UTF8(title_field, "type", "autocomplete");
    BSON_APPEND_UTF8(title_field, "analyzer", "lucene.standard");
    BSON_APPEND_UTF8(title_field, "tokenization", "edgeGram");
    BSON_APPEND_INT32(title_field, "minGrams", 3);
    BSON_APPEND_INT32(title_field, "maxGrams", 5);
    BSON_APPEND_BOOL(title_field, "foldDiacritics", false);

    // Add title field to fields object
    BSON_APPEND_DOCUMENT(fields, "title", title_field);

    // Build mappings object
    BSON_APPEND_BOOL(mappings, "dynamic", false);
    BSON_APPEND_DOCUMENT(mappings, "fields", fields);

    // Add mappings to definition
    BSON_APPEND_DOCUMENT(definition, "mappings", mappings);

    // Build the complete index specification
    BSON_APPEND_UTF8(index_spec, "name", "partial-match-tutorial-autocomplete");
    BSON_APPEND_DOCUMENT(index_spec, "definition", definition);

    printf("Creating search index...\n");

    // Create the search index
    result = mongoc_collection_create_search_index(collection, index_spec, NULL, &index_name, &error);

    if (!result) {
        fprintf(stderr, "Failed to create search index: %s\n", error.message);
        bson_destroy(index_spec);
        bson_destroy(definition);
        bson_destroy(mappings);
        bson_destroy(fields);
        bson_destroy(title_field);
        mongoc_collection_destroy(collection);
        mongoc_database_destroy(database);
        cleanup_mongodb(client);
        return EXIT_FAILURE;
    }

    printf("New index name: %s\n", index_name);

    // Cleanup
    bson_free(index_name);
    bson_destroy(index_spec);
    bson_destroy(definition);
    bson_destroy(mappings);
    bson_destroy(fields);
    bson_destroy(title_field);
    mongoc_collection_destroy(collection);
    mongoc_database_destroy(database);
    cleanup_mongodb(client);

    printf("Successfully created autocomplete search index\n");
    return EXIT_SUCCESS;
}

Compile and run the program.

gcc -o create_index create_index.c $(pkg-config --cflags --libs libmongoc-1.0)
./create_index

Run a Case-Sensitive Partial Match Query

  1. Create a file named partial-match-tutorial-query.c.

  2. Copy and paste one of the following queries into the partial-match-tutorial-query.c file.

### autocomplete

The following query searches for documents where the title field contains words that begin with Great.

```c #include #include #include #include

// MongoDB connection URI #define MONGODB_URI ""

// Database and collection names #define DATABASE_NAME "sample_mflix" #define COLLECTION_NAME "movies"

mongoc_client_t connect_to_mongodb(void) { mongoc_client_t client; mongoc_uri_t *uri; bson_error_t error;

   // Initialize MongoDB C driver
   mongoc_init();

   // Create a MongoDB URI object
   uri = mongoc_uri_new_with_error(MONGODB_URI, &error);
   if (!uri) {
       fprintf(stderr, "Failed to parse URI: %s\n", error.message);
       return NULL;
   }

   // Create a new client instance
   client = mongoc_client_new_from_uri(uri);
   if (!client) {
       fprintf(stderr, "Failed to create MongoDB client\n");
       mongoc_uri_destroy(uri);
       return NULL;
   }

   // Configure the client for server API version
   mongoc_client_set_error_api(client, 2);

   mongoc_uri_destroy(uri);
   return client;

}

void cleanup_mongodb(mongoc_client_t *client) { if (client) { mongoc_client_destroy(client); } mongoc_cleanup(); }

void print_bson_document(const bson_t doc) { char json_string = bson_as_canonical_extended_json(doc, NULL); printf("%s\n", json_string); bson_free(json_string); }

int main(void) { mongoc_client_t client; mongoc_database_t database; mongoc_collection_t collection; mongoc_cursor_t cursor; bson_t pipeline; bson_t search_stage; bson_t limit_stage; bson_t project_stage; const bson_t *doc; bson_error_t error;

   // Connect to MongoDB
   client = connect_to_mongodb();
   if (!client) {
       return EXIT_FAILURE;
   }

   printf("Connected to MongoDB Atlas\n");

   // Get database and collection
   database = mongoc_client_get_database(client, DATABASE_NAME);
   collection = mongoc_client_get_collection(client, DATABASE_NAME, COLLECTION_NAME);

   // Create aggregation pipeline
   pipeline = bson_new();

   // Create $search stage
   search_stage = bson_new();
   bson_t *search_spec = bson_new();
   bson_t *autocomplete_spec = bson_new();

   BSON_APPEND_UTF8(autocomplete_spec, "query", "Great");
   BSON_APPEND_UTF8(autocomplete_spec, "path", "title");

   BSON_APPEND_UTF8(search_spec, "index", "partial-match-tutorial-autocomplete");
   BSON_APPEND_DOCUMENT(search_spec, "autocomplete", autocomplete_spec);

   BSON_APPEND_DOCUMENT(search_stage, "$search", search_spec);

   // Create $limit stage
   limit_stage = bson_new();
   BSON_APPEND_INT32(limit_stage, "$limit", 10);

   // Create $project stage
   project_stage = bson_new();
   bson_t *project_spec = bson_new();
   BSON_APPEND_INT32(project_spec, "_id", 0);
   BSON_APPEND_INT32(project_spec, "title", 1);
   BSON_APPEND_DOCUMENT(project_stage, "$project", project_spec);

   // Build the pipeline array
   bson_t *stage_array = bson_new();
   BSON_APPEND_DOCUMENT(stage_array, "0", search_stage);
   BSON_APPEND_DOCUMENT(stage_array, "1", limit_stage);
   BSON_APPEND_DOCUMENT(stage_array, "2", project_stage);

   BSON_APPEND_ARRAY(pipeline, "pipeline", stage_array);

   printf("Running autocomplete search query...\n");

   // Execute the aggregation
   cursor = mongoc_collection_aggregate(collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL);

   if (!cursor) {
       fprintf(stderr, "Failed to execute aggregation\n");
       goto cleanup;
   }

   printf("Results:\n");

   // Iterate through results
   while (mongoc_cursor_next(cursor, &doc)) {
       print_bson_document(doc);
   }

   // Check for errors
   if (mongoc_cursor_error(cursor, &error)) {
       fprintf(stderr, "Cursor error: %s\n", error.message);
   }

cleanup: // Cleanup if (cursor) { mongoc_cursor_destroy(cursor); } bson_destroy(pipeline); bson_destroy(search_stage); bson_destroy(limit_stage); bson_destroy(project_stage); bson_destroy(search_spec); bson_destroy(autocomplete_spec); bson_destroy(project_spec); bson_destroy(stage_array); mongoc_collection_destroy(collection); mongoc_database_destroy(database); cleanup_mongodb(client);

   printf("Autocomplete query completed\n");
   return EXIT_SUCCESS;

}

```

  1. Replace the <connection-string> in the query and then save the file.

Ensure that your connection string includes your database user's credentials. To learn more, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver

  1. Compile and run the program to query your collection.

bash gcc -o partial-match-tutorial-query partial-match-tutorial-query.c $(pkg-config --cflags --libs libmongoc-1.0) ./partial-match-tutorial-query

This tutorial describes how to create an index on the sample_mflix.movies collection and run partial string queries against the plot field using the Atlas UI.

To return matches for partial string queries, you can use one of the following operators:

  • The [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref operator, which allows you to search the specified fields for a word or phrase that contains the sequence of characters that you specify with your query.

  • The [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref operator, which allows you to search the specified fields for documents that contain the terms in your query string at the distance you specify between the terms.

  • The [regex](https://www.mongodb.com/docs/search/query/operators-collectors/regex.md#std-label-regex-ref operator, which allows you to search the specified fields for strings using regular expression.

  • The [wildcard](https://www.mongodb.com/docs/search/query/operators-collectors/wildcard.md#std-label-wildcard-ref operator, which allows you to search the specified fields using special characters in your query to match any character.

You can also use the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator with a custom analyzer for more fine-grained control over partial matching. To learn more, see [Custom Analyzers.](https://www.mongodb.com/docs/search/indexes/analyzers/custom.md#std-label-custom-analyzers

This tutorial takes you through the following steps:

  1. Set up a MongoDB Search index on the plot field in the sample_mflix.movies collection.

  2. Run MongoDB Search query for a partial string against the plot field in the sample_mflix.movies collection using [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref, [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref, [regex](https://www.mongodb.com/docs/search/query/operators-collectors/regex.md#std-label-regex-ref, and [wildcard](https://www.mongodb.com/docs/search/query/operators-collectors/wildcard.md#std-label-wildcard-ref operators.

Before you begin, ensure that your cluster meets the following requirements.

To complete the tutorials, you must have:

  • An Atlas cluster with MongoDB version 6.0 or later or a MongoDB self-managed cluster with MongoDB version 8.2 or later.

  • The [sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data loaded into your cluster.

  • [Project Data Access Admin](https://www.mongodb.com/docs/atlas/reference/user-roles.md#mongodb-authrole-Project-Data-Access-Admin or higher access to your project to create MongoDB Search indexes.

  • Search Tester, [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh, Compass, or a supported MongoDB Driver to run queries on your cluster.

Note:

You can run MongoDB Search queries by using any driver through the [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search aggregation stage. These tutorials include examples for a selection of clients. Refer to the specific tutorial page for details.

You can also complete these tutorials with local deployments that you create with the Atlas CLI or with an on-prem deployment. To learn more, see Create a Local Atlas Deployment and [Self-Managed Deployments.](https://www.mongodb.com/docs/manual/self-managed-deployments.md#std-label-self-managed-deployments

Continue Learning

To learn more about how to implement partial matches, see MongoDB Text Search: Substring Pattern Matching Including Regex and Wildcard, Use Search Instead.

Create the MongoDB Search Index

Install the MongoDB Node.js Driver.

For installation instructions, see the MongoDB Node.js Driver documentation.

Create the index.

autocomplete

Create a file named create_auto_complete_index.js and paste the following code:

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

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

const client = new MongoClient(uri);

async function run() {
  try {

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

    // define your MongoDB Search index
    const index = {
      name: "partial-match-tutorial-autocomplete",
      definition: {
        /* search index definition fields */
        "mappings": {
          "dynamic": false,
          "fields": {
            "title": {
              "type": "autocomplete",
              "analyzer": "lucene.standard",
              "tokenization": "edgeGram",
              "minGrams": 3,
              "maxGrams": 5,
              "foldDiacritics": false
            }
          }
        }
      }
    }

    // run the helper method
    const result = await collection.createSearchIndex(index);
    console.log("New index name: " + result);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);

Run the program.

node create_auto_complete_index.js
## or
node create_string_index.js

Run a Case-Sensitive Partial Match Query

  1. Create a file named partial-match-tutorial-query.js.

  2. Copy and paste one of the following queries into the partial-match-tutorial-query.js file.

### autocomplete

The following query searches for documents where the title field contains words that begin with Great.

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

// connect to your Atlas cluster const uri = "";

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:
             {
               index: "partial-match-tutorial-autocomplete",
               autocomplete:
                 {
                   query: "Great",
                   path: "title"
                 }
               }
           },
           {$limit: 10},
           {$project: {_id: 0,title: 1}}
       ];
       // run pipeline
       const result = await coll.aggregate(agg);
       console.log(result)

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

} run().catch(console.dir);

```

  1. Replace the <connection-string> in the query and then save the file.

Ensure that your connection string includes your database user's credentials. To learn more, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver

  1. Run the command to query your collection.

bash node partial-match-tutorial-query.js

This tutorial describes how to create an index on the sample_mflix.movies collection and run partial string queries against the plot field using the Atlas UI.

To return matches for partial string queries, you can use one of the following operators:

  • The [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref operator, which allows you to search the specified fields for a word or phrase that contains the sequence of characters that you specify with your query.

  • The [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref operator, which allows you to search the specified fields for documents that contain the terms in your query string at the distance you specify between the terms.

  • The [regex](https://www.mongodb.com/docs/search/query/operators-collectors/regex.md#std-label-regex-ref operator, which allows you to search the specified fields for strings using regular expression.

  • The [wildcard](https://www.mongodb.com/docs/search/query/operators-collectors/wildcard.md#std-label-wildcard-ref operator, which allows you to search the specified fields using special characters in your query to match any character.

You can also use the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator with a custom analyzer for more fine-grained control over partial matching. To learn more, see [Custom Analyzers.](https://www.mongodb.com/docs/search/indexes/analyzers/custom.md#std-label-custom-analyzers

This tutorial takes you through the following steps:

  1. Set up a MongoDB Search index on the plot field in the sample_mflix.movies collection.

  2. Run MongoDB Search query for a partial string against the plot field in the sample_mflix.movies collection using [autocomplete](https://www.mongodb.com/docs/search/query/operators-collectors/autocomplete.md#std-label-autocomplete-ref, [phrase](https://www.mongodb.com/docs/search/query/operators-collectors/phrase.md#std-label-phrase-ref, [regex](https://www.mongodb.com/docs/search/query/operators-collectors/regex.md#std-label-regex-ref, and [wildcard](https://www.mongodb.com/docs/search/query/operators-collectors/wildcard.md#std-label-wildcard-ref operators.

Before you begin, ensure that your cluster meets the following requirements.

To complete the tutorials, you must have:

  • An Atlas cluster with MongoDB version 6.0 or later or a MongoDB self-managed cluster with MongoDB version 8.2 or later.

  • The [sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data loaded into your cluster.

  • [Project Data Access Admin](https://www.mongodb.com/docs/atlas/reference/user-roles.md#mongodb-authrole-Project-Data-Access-Admin or higher access to your project to create MongoDB Search indexes.

  • Search Tester, [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh, Compass, or a supported MongoDB Driver to run queries on your cluster.

Note:

You can run MongoDB Search queries by using any driver through the [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search aggregation stage. These tutorials include examples for a selection of clients. Refer to the specific tutorial page for details.

You can also complete these tutorials with local deployments that you create with the Atlas CLI or with an on-prem deployment. To learn more, see Create a Local Atlas Deployment and [Self-Managed Deployments.](https://www.mongodb.com/docs/manual/self-managed-deployments.md#std-label-self-managed-deployments

Continue Learning

To learn more about ho

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