Docs Menu
Docs Home
/
Atlas
/ /

Manage Atlas Search Indexes

An Atlas Search index is a data structure that categorizes data into an easily searchable format. It is a mapping between terms and the documents that contain those terms. Atlas Search indexes enable faster retrieval of documents using certain identifiers. You must configure an Atlas Search index to query data in your Atlas cluster using Atlas Search.

You can create an Atlas Search index on a single field or on multiple fields. We recommend that you index the fields that you regularly use to sort or filter your data in order to quickly retrieve the documents that contain the relevant data at query-time.

If you make changes to the collection for which you defined Atlas Search indexes, the latest data might not be available immediately for queries. However, mongot monitors the change streams, which allows it to update stored copies of data, and Atlas Search indexes are eventually consistent.

When you change an index definition, mongot automatically rebuilds the new index in the background, while continuing to serve queries with the old index to make sure there is no downtime. This happens when you deploy mongot and mongod processes on the same node and when you deploy the processes on different nodes. Atlas also rebuilds indexes when you enable or disable Encryption at Rest.

If you change the topology of your search deployment, Atlas Search provisions and builds indexes on any new nodes before removing old nodes, to ensure there is no query downtime.

For deployments where both the mongod and mongot processes run on the same node, if Atlas Search introduces changes that require rebuilding your indexes (such as some Atlas Search features that require an index update), Atlas automatically deploys additional nodes for free to build the indexes, while the old nodes continue to serve your queries.

Warning

If you shard a collection that already has an Atlas Search index, you might experience a brief period of query downtime when the collection begins to appear on a shard. Also, if you add a shard for an already sharded collection that contains an Atlas Search index, your search queries against that collection will fail until the initial sync process completes on the added shards. To learn more, see initial sync process.

Important

If you use the $out aggregation stage to modify a collection with an existing Atlas Search index, you must delete and re-create the search index. If possible, consider using $merge instead of $out.

You can deploy dedicated Search Nodes to improve performance, scalability, and resource isolation. If you've deployed Search Nodes, consider the following:

  • Adding and adjusting shards triggers a rebuild of the Atlas Search index. During this index rebuild, the index might not have the most current data. Therefore, queries against data on those shards might fail or return incorrect results.

  • If you reshard a collection with Atlas Search indexes, Atlas Search indexes on the collection become unavailable when the resharding operation completes. You must delete and create new Atlas Search indexes once the operation is complete.

  • If you issue the command to change the primary shard of a database, the Atlas Search indexes for any unsharded collection under this database become unavailable once the operation completes. You must delete and create new Atlas Search indexes once the movePrimary operation is complete.

To learn more about Atlas Search node architecture, see Atlas Search Deployment Options.

You can assign Project User Roles or Database User Roles to provide access to the user privileges necessary to perform Atlas Search index actions described in this guide.

The following table shows the modes of access that the following Project Roles support for the specified Atlas Search actions:

Role
Atlas Search Action
Atlas UI
Atlas CLI
Atlas API [1]

To view Atlas Search indexes and analyzers.

To create, view, update, and delete Atlas Search indexes and analyzers.

To create, view, update, and delete Atlas Search indexes.

[1] Each role grants permission to call either a subset or the full set of Atlas Search API endpoints in the Atlas Administration API. See the Atlas Search Action column for descriptions of the API endpoints that each role grants access to.

The following MongoDB Database Roles support the given Atlas Search Index Privilege Actions:

Action Description
Database Roles
Atlas Search Index Privilege Action

View Atlas Search index

Create Atlas Search index

Edit Atlas Search index

Delete Atlas Search index

To learn more, see Built-in Roles or Specific Privileges.

The following tutorial describes how to create an Atlas Search index using your selected method.

To see an example tutorial that creates an index for the sample_mflix.movies collection, see Atlas Search Quick Start. For a conceptual overview of how to define an index to meet your query preferences, see Define Your Index.

You can also use Atlas Search with local Atlas deployments that you create with the Atlas CLI. To learn more, see Create a Local Atlas Deployment.


Use the Select your language drop-down menu to set the language of the procedure in this section.


To create an Atlas Search index using the Atlas Search API:

1

Send a POST request to the search/indexes endpoint.

curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
--header "Accept: application/json" \
--header "Content-Type: application/json" \
--include \
--request POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
--data '
{
"collectionName": "<collection-name>",
"database": "<database-name>",
"name": "<index-name>",
"type": "search",
"definition":
{
"analyzer": "<analyzer-name>",
"searchAnalyzer": "<analyzer-name>",
"mappings": {
"dynamic": <boolean>,
"fields": { <field-definition> }
},
"numPartitions": <integer>,
"analyzers": [ {
<custom-analyzer-definition>
}
],
"storedSource": <boolean> | {
<stored-source-definition>
},
"synonyms": [
{
<synonym-mapping-definition>
}
]
}
}'

To learn more about the syntax and parameters for this endpoint, see Create One.

2

Note

Atlas doesn't create the index if the collection doesn't exist, but it still returns a 200 status.

To create an Atlas Search index using the Atlas CLI:

To create a search index for a cluster using the Atlas CLI, run the following command:

atlas clusters search indexes create [indexName] [options]

To learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas clusters search indexes create.

To create a search index for the specified deployment using the Atlas CLI, run the following command:

atlas deployments search indexes create [indexName] [options]

To learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas deployments search indexes create.

To learn more about how to use the Atlas CLI to create a local Atlas deployment, see Create a Local Atlas Deployment.

Tip

See: Related Links

The following example shows you how to use the atlas clusters or atlas deployments command to create an Atlas Search index in non-interactive mode with a configuration file.

1
{
"collectionName": "movies",
"database": "sample_mflix",
"definition": {
"mappings": {
"dynamic": true
},
},
"name": "searchIndex"
}
2
  1. Run one of the following commands.

    Cloud Deployment:

    atlas clusters search indexes create --file indexDef.json

    Local Deployment:

    atlas deployments search indexes create --file indexDef.json
  2. Specify the deployment and press Enter.

To create an Atlas Search index using the Atlas UI:

1

Warning

Navigation Improvements In Progress

We're currently rolling out a new and improved navigation experience. If the following steps don't match your view in the Atlas UI, see the preview documentation.

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

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

  3. If it's not already displayed, click Clusters in the sidebar.

    The Clusters page displays.

2

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

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

    If you have no clusters, click Create cluster to create one. To learn more, see Create a Cluster.

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

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3
4

Make the following selections on the page and then click Next.

Search Type

Select the Atlas Search index type.

Index Name and Data Source

Specify the following information:

  • Index Name: default

  • Database and Collection:

    • name of the database

    • name of the collection

Configuration Method

For a guided experience, select Visual Editor.

To edit the raw index definition, select JSON Editor.

Note

Your Atlas Search index is named default by default. If you keep this name, then your index will be the default Search index for any Atlas Search query that does not specify a different index option in its operators. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.

5

The default index definition is a dynamic mapping of the fields in the documents and will work with any collection.

To customize your index definition, review the following index configurations:

Visual Editor Field
Description
Necessity

Index Analyzer

Specify the analyzer to use for indexing the collection data. By default, Atlas Search uses the standard analyzer (lucene.standard).

Corresponds to the analyzer JSON setting.

Optional

Search Analyzer

Specifies the analyzer to apply to query text before searching the text. If you omit this field, the index inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

Corresponds to the searchAnalyzer JSON setting.

Optional

Dynamic Mapping

Specify dynamic or static mapping of fields.

By default, dynamic mapping is enabled. To disable dynamic mapping, set dynamic to Off. If you disable dynamic mapping, you must specify the fields to index.

To learn more about dynamic and static mappings, see Define Field Mappings.

Corresponds to the mappings.dynamic JSON setting.

Required

Field Name
Description
Necessity

analyzer

Specify the analyzer to use for indexing the collection data. By default, Atlas Search uses the standard analyzer (lucene.standard).

Optional

searchAnalyzer

Specifies the analyzer to apply to query text before searching the text. If you omit this field, the index inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

Optional

mappings.dynamic

Specify dynamic or static mapping of fields. To disable dynamic mapping, set "dynamic": to false. By default, dynamic mapping is enabled. If you disable dynamic mapping, you must specify the fields to index. To learn more about dynamic and static mappings, see Index Reference.

Required

To learn more about these index definition settings, see Index Reference.

If you are satisfied with the default configuration, skip ahead. If you wish to refine your Atlas Search index, proceed to the next step.

6
  1. Click Refine Your Index to make changes to any of the following settings.

    Field Name
    Description
    Necessity

    Field Mappings

    Required if Dynamic Mapping in the Index Configurations section is disabled.

    Specify the fields to index:

    1. Click Add Field Mapping to open the Add Field Mapping window.

    2. Specify the following information about the field:

      • Field name - Name of the field to index.

      • Data Type - Field data type. To learn more about the supported data types and their options, see Data Types.

    3. (Optional) Specify additional properties.

      A table of additional configuration options appears in the Add Field Mapping window. These properties depend on the data type that you selected in the last step.

      To learn more about the supported data types and their options, see Data Types.

    4. (Optional) Add multi field.

      Click Add Multi Field to configure an alternative field analyzer with which to index the field. To learn more, see Multi Analyzer.

    5. Click Add to add the field.

      You can click the ellipses (...) icon for the field in the Actions column to do the following:

      • Click Edit to modify the configuration.

      • Click Add Data Type to configure additional data types for the field.

      • Click Delete to remove the field from the index.

    To learn more about defining field mappings, see Index Reference.

    Corresponds to the mappings.fields JSON setting.

    Conditional

    Stored Source Fields

    Specify the fields to store on Atlas Search for query-time lookups. You can store fields of all supported Data Types on Atlas Search.

    To learn more about storing fields, see Define Stored Source Fields in Your Atlas Search Index.

    Corresponds to the storedSource JSON setting.

    Optional

    Synonyms Mappings

    Specify synonym mappings to use in your index.

    You can use a synonym mapping to query only fields analyzed with the same analyzer.

    To learn more about synonym mappings, see Define Synonym Mappings in Your Atlas Search Index.

    Corresponds to the synonyms JSON setting.

    Optional.

    Index Partitions

    The number of partitions to use if field objects exceed 2.1 billion.

    Corresponds to the numPartitions JSON setting.

    Optional.

  2. Click Save Changes.

  1. Add any of the following settings to your index:

    Field Name
    Description
    Necessity

    mappings.fields

    Required if mappings.dynamic is false.

    Specify the fields that you would like to index. To learn more, see Define Field Mappings.

    Conditional

    storedSource

    Specify the fields to store on Atlas Search for query-time lookups. You can store fields of all supported Data Types on Atlas Search.

    To learn more about storing fields, see Define Stored Source Fields in Your Atlas Search Index.

    Optional

    synonyms

    Specify synonym mappings to use in your index.

    You can use a synonym mapping to query only fields analyzed with the same analyzer.

    To learn more about synonym mappings, see Define Synonym Mappings in Your Atlas Search Index.

    Optional

    numPartitions

    The number of partitions to use if field objects exceed 2.1 billion.

    Optional.

    To learn more about these index definition settings, see Index Reference.

  2. Click Next.

7

Note

You can't save the default index definition as a draft. If you use the Visual Editor and your index definition contains static mappings, you can save an index definition as a draft.

  1. Click Cancel.

  2. Click Save Draft or Delete Draft.

    Important

    You can't create a new index when you have a pending index draft.

    To learn more, see Resume or Delete an Atlas Search Index Draft.

8

Atlas displays a Toast (brief, non-interactive notification) to let you know your index is building.

9

The newly created index appears on the Atlas Search tab. While the index is building, the Status field reads Build in Progress. When the index is finished building, the Status field reads Active.

Note

Larger collections take longer to index. You will receive an email notification when your index is finished building.

To create an Atlas Search index using mongosh:

1

To learn more, see Connect via mongosh.

2

Use the db.collection.createSearchIndex() method.

The command has the following syntax. If you omit the index name, Atlas Search names the index default. To learn more, see Index Reference.

db.<collection>.createSearchIndex(
"<index-name>",
{
/* search index definition */
}
)

Example

To create an index named example-index that dynamically indexes the fields in the movies collection, run the following command:

db.movies.createSearchIndex(
"example-index",
{ mappings: { dynamic: true } }
)
example-index

To create an Atlas Search index using MongoDB Compass:

1

Open Compass and connect to your Atlas cluster. For detailed instructions, see Connect via Compass.

2

On the Database screen, click the name of the database, then click the name of the collection.

3
  1. Click the Indexes tab, then select Search Indexes.

  2. Click Create Index to open the index creation dialog box.

  3. Specify a name for the index.

    Your Atlas Search index is named default by default. If you keep this name, then your index will be the default Search index for any Atlas Search query that does not specify a different index option in its operators. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.

  4. Specify the JSON Atlas Search index definition.

    1{
    2 "analyzer": "<analyzer-for-index>",
    3 "searchAnalyzer": "<analyzer-for-query>",
    4 "mappings": {
    5 "dynamic": <boolean>,
    6 "fields": { <field-definition> }
    7 },
    8 "numPartitions": <integer>,
    9 "analyzers": [ <custom-analyzer> ],
    10 "storedSource": <boolean> | {
    11 <stored-source-definition>
    12 },
    13 "synonyms": [
    14 {
    15 <synonym-mapping-definition>
    16 }
    17 ]
    18}
    19
  5. Click Create Search Index.

To use the C Driver to create an Atlas Search index, define the search index in your application and call the mongoc_collection_command_simple() method.

Note

The Atlas Search index management methods run asynchronously. The driver methods can return before confirming that they ran successfully. To determine the current status of the search indexes, run an aggregation operation with the $listSearchIndexes pipeline stage.

1
2

The following sample application specifies the createSearchIndexes command to define a search index. Then, the application converts the command and search index information to BSON and passes this information to the mongoc_collection_command_simple() method to create the search index. To learn more, see Index Reference.

#include <mongoc/mongoc.h>
#include <stdlib.h>
int main (void)
{
mongoc_client_t *client = NULL;
mongoc_collection_t *collection = NULL;
mongoc_database_t *database = NULL;
bson_error_t error;
bson_t cmd = BSON_INITIALIZER;
bool ok = true;
mongoc_init();
// Connect to your Atlas deployment
client = mongoc_client_new("<connectionString>");
if (!client) {
fprintf(stderr, "Failed to create a MongoDB client.\n");
ok = false;
goto cleanup;
}
// Access your database and collection
database = mongoc_client_get_database(client, "<databaseName>");
collection = mongoc_database_get_collection(database, "<collectionName>");
// Specify the command and the new index
const char *cmd_str = BSON_STR({
"createSearchIndexes" : "<collectionName>",
"indexes" : [ {
"name" : "<indexName>",
"definition" : {
"analyzer": "<indexAnalyzer>",
"searchAnalyzer": "<queryAnalyzer>",
"mappings": {
"dynamic": <boolean>,
"fields": { <fieldDefinition> }
},
"numPartitions": <integer>,
"analyzers": [ <customAnalyzer> ],
"storedSource": <boolean> | {
<storedSourceDefinition>
},
"synonyms": [
{
<synonymMappingDefinition>
}
]
}
} ]
});
// Convert your command to BSON
if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) {
fprintf(stderr, "Failed to parse command: %s\n", error.message);
ok = false;
goto cleanup;
}
// Create the Atlas search index by running the command
if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) {
fprintf(stderr, "Failed to run createSearchIndexes: %s\n", error.message);
ok = false;
goto cleanup;
}
printf ("Index created!\n");
cleanup:
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_database_destroy (database);
bson_destroy (&cmd);
mongoc_cleanup ();
return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}

The following sample application uses the createSearchIndexes command to define multiple search indexes. Then, the application converts the command and search index information to BSON and passes this information to the mongoc_collection_command_simple() method to create the search index. To learn more, see Index Reference.

#include <mongoc/mongoc.h>
#include <stdlib.h>
int main (void)
{
mongoc_client_t *client = NULL;
mongoc_collection_t *collection = NULL;
mongoc_database_t *database = NULL;
bson_error_t error;
bson_t cmd = BSON_INITIALIZER;
bool ok = true;
mongoc_init();
// Connect to your Atlas deployment
client = mongoc_client_new("<connectionString>");
if (!client) {
fprintf(stderr, "Failed to create a MongoDB client.\n");
ok = false;
goto cleanup;
}
// Access your database and collection
database = mongoc_client_get_database(client, "<databaseName>");
collection = mongoc_database_get_collection(database, "<collectionName>");
// Specify the command and the new indexes
const char *cmd_str = BSON_STR({
"createSearchIndexes" : "<collectionName>",
"indexes" : [{
// Add your search index definition fields here
"name" : "<firstIndexName>"
},
{
// Add your search index definition fields here
"name" : "<secondIndexName>"
}]
});
// Convert your command to BSON
if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) {
fprintf(stderr, "Failed to parse command: %s\n", error.message);
ok = false;
goto cleanup;
}
// Create the Atlas search indexes by running the command
if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) {
fprintf(stderr, "Failed to run createSearchIndexes: %s\n", error.message);
ok = false;
goto cleanup;
}
printf ("Indexes created!\n");
cleanup:
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_database_destroy (database);
bson_destroy (&cmd);
mongoc_cleanup ();
return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}
3
  • Your Atlas connection string. To learn more, see Connect via Drivers.

  • The database and collection for which you want to create the index.

  • The name of your index. If you omit the index name, Atlas Search names the index default.

  • The search index definition. To learn more, see Index Reference.

4
gcc -o create-index create-index.c $(pkg-config --libs --cflags libmongoc-1.0)
./create-index

To use the C++ Driver to create an Atlas Search index, define the search index in your application and call the create_one() method.

Note

The Atlas Search index management methods run asynchronously. The driver methods can return before confirming that they ran successfully. To determine the current status of the search indexes, call the list() method on a search index view instance.

1
2

The following sample application passes a search index name and definition to the search_index_model() method to dynamically index the fields in your collection. Then, the application passes the search index specifications to the create_one() method to create the search index. To learn more, see Index Reference.

#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/search_index_view.hpp>
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;
using namespace mongocxx;
int main()
{
try
{
// Connect to your Atlas deployment
mongocxx::instance instance{};
mongocxx::uri uri("<connectionString>");
mongocxx::client client(uri);
// Access your database and collection
auto db = client["<databaseName>"];
auto collection = db["<collectionName>"];
// Create an index model with your index name and definition
auto siv = collection.search_indexes();
auto name = "<indexName>";
auto definition = make_document(kvp("mappings", make_document(kvp("dynamic", true))));
auto model = search_index_model(name, definition.view());
// Create the search index
siv.create_one(model);
std::cout << "Index created!" << std::endl;
}
catch (const std::exception& e)
{
std::cout<< "Exception: " << e.what() << std::endl;
}
return 0;
}

You can also create multiple Atlas Search indexes at once. For each search index you want to create, pass the search index specifications to the search_index_model() method. Then, add each search index to a vector and pass the vector to the create_many() method to create the search indexes:

#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/search_index_view.hpp>
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;
using namespace mongocxx;
int main()
{
try
{
// Connect to your Atlas deployment
mongocxx::instance instance{};
mongocxx::uri uri("<connectionString>");
mongocxx::client client(uri);
// Access your database and collection
auto db = client["<databaseName>"];
auto collection = db["<collectionName>"];
// Create index models and add them to a vector
auto siv = collection.search_indexes();
std::vector<search_index_model> models;
auto name1 = "<firstIndexName>";
auto definition1 = make_document(/* Add search index definition fields here */);
auto model1 = search_index_model(name1, definition1.view());
models.push_back(model1);
auto name2 = "<secondIndexName>";
auto definition2 = make_document(/* Add search index definition fields here */);
auto model2 = search_index_model(name2, definition2.view());
models.push_back(model2);
// Create the search indexes
siv.create_many(models);
std::cout << "Indexes created!" << std::endl;
}
catch (const std::exception& e)
{
std::cout<< "Exception: " << e.what() << std::endl;
}
return 0;
}
3
  • Your Atlas connection string. To learn more, see Connect via Drivers.

  • The database and collection for which you want to create the index.

  • The name of your index. If you omit the index name, Atlas Search names the index default.

4
g++ -o create-index create-index.cpp $(pkg-config --cflags --libs libmongocxx)
./create-index

To use the .NET/C# Driver to create an Atlas Search index:

  1. Construct a BsonDocument that defines the index.

  2. Pass the BsonDocument to the CreateOne() or CreateOneAsync() method.

1
  1. Run the following command to create a new directory called csharp-create-index.

    mkdir csharp-create-index
  2. Run the following command to change to the new directory.

    cd csharp-create-index
  3. Run the following command to initialize your project.

    dotnet new console
2

Run the following command:

dotnet add package MongoDB.Driver
3

Replace the placeholder values in the following example application, which uses the SearchIndexes.CreateOne command to define an Atlas Search index:

Value
Description

<connection-string>

Your Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

Database for which you want to create the index.

<collectionName>

Collection for which you want to create the index.

<IndexName>

The name of your index. If you omit the index name, Atlas Search names the index default.

<IndexDefinition>

The definition of your index. To learn about index definition syntax, see Index Reference.

1using MongoDB.Bson;
2using MongoDB.Driver;
3
4// connect to your Atlas deployment
5var uri = "<connection-string>";
6
7var client = new MongoClient(uri);
8
9var db = client.GetDatabase("<databaseName>");
10var collection = db.GetCollection<BsonDocument>("<collectionName>");
11
12// define your Atlas Search index
13var index = new BsonDocument
14{
15 { "mappings", new BsonDocument
16 {
17 { "dynamic", true }
18 }
19 }
20};
21
22var result = collection.SearchIndexes.CreateOne(index, "<indexName>");
23Console.WriteLine(result);

Replace the placeholder values in the following example application, which uses the SearchIndexes.CreateMany command to define an Atlas Search index:

Value
Description

<connection-string>

Your Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

Database for which you want to create the index.

<collectionName>

Collection for which you want to create the index.

<firstIndexName>

Name of your first index.

<lastIndexName>

Name of your last index.

<IndexDefinition>

The definition of your index. To learn about index definition syntax, see Index Reference.

1using MongoDB.Bson;
2using MongoDB.Driver;
3
4// connect to your Atlas deployment
5var uri = "<connection-string>";
6
7var client = new MongoClient(uri);
8
9var db = client.GetDatabase("<databaseName>");
10var collection = db.GetCollection<BsonDocument>("<collectionName>");
11
12// define your Atlas Search indexes
13var indexes = new List<CreateSearchIndexModel>
14{
15 new CreateSearchIndexModel(
16 "<firstIndexName>",
17 new BsonDocument
18 {
19 <IndexDefinition>// search index definition fields
20 }
21 ),
22 ...
23 new CreateSearchIndexModel(
24 "<lastIndexName>",
25 new BsonDocument
26 {
27 <IndexDefinition> // search index definition fields
28 }
29 )
30};
31
32var result = collection.SearchIndexes.CreateMany(indexes);
4

Use the following command to run the project:

dotnet run csharp-create-index.csproj
default

Tip

API Documentation

To learn more about the methods on this page, see the API documentation for the .NET/C# driver.

To use the Java Driver to create an Atlas Search index, construct a document that defines the search index, and then pass the document to the createSearchIndex() or createSearchIndexes() method.

Note

The Atlas Search index management methods run asynchronously. The driver methods can return before confirming that they ran successfully. To determine the current status of the indexes, call the listSearchIndexes() method.

1
2

The following sample application defines a search index to dynamically index the fields in your collection, and then runs the createSearchIndex() method to create the index. To learn more, see Index Reference.

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 CreateIndex {
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("<databaseName>");
MongoCollection<Document> collection = database.getCollection("<collectionName>");
Document index = new Document("mappings",
new Document("dynamic", true));
collection.createSearchIndex("<index-name>", index);
}
}
}

You can use the following sample application to create multiple Atlas Search indexes at once. To do so, construct a document for each search index that you wish to create, and then pass the documents as an array to the createSearchIndexes() method:

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.SearchIndexModel;
import org.bson.Document;
import java.util.Arrays;
public class CreateIndex {
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("<databaseName>");
MongoCollection<Document> collection = database.getCollection("<collectionName>");
SearchIndexModel indexOne = new SearchIndexModel("<first-index-name>",
new Document(
// search index definition fields
));
SearchIndexModel indexTwo = new SearchIndexModel("<second-index-name>",
new Document(
// search index definition fields
));
collection.createSearchIndexes(Arrays.asList(indexOne, indexTwo));
}
}
}
3
  • Your Atlas connection string. To learn more, see Connect via Drivers.

  • The database and collection for which you want to create the index.

  • The names of your indexes. If you omit an index's name, Atlas Search names the index default.

4
javac CreateIndex.java
java CreateIndex

To create an Atlas Search index through the Node Driver:

  1. Define the search index from your application.

  2. Run the createSearchIndex or createSearchIndexes helper method.

1
2

Replace the placeholder values in the following example application named create-index.js, which uses the createSearchIndex command to define an Atlas Search index:

Value
Description

<connectionString>

Your Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

Database for which you want to create the index.

<collectionName>

Collection for which you want to create the index.

<indexName>

Name of your index. If you omit the index name, Atlas Search names the index default.

<IndexDefinition>

The definition of your index. To learn about index definition syntax, see Index Reference.

create-index.js
import { MongoClient } from "mongodb";
// connect to your Atlas deployment
const uri = "<connectionString>";
const client = new MongoClient(uri);
async function run() {
try {
const database = client.db("<databaseName>");
const collection = database.collection("<collectionName>");
// define your Atlas Search index
const index = {
name: "<indexName>",
definition: {
/* search index definition fields */
<indexDefinition>
}
}
// run the helper method
const result = await collection.createSearchIndex(index);
console.log(result);
} finally {
await client.close();
}
}
run().catch(console.dir);
Value
Description

<connectionString>

Your Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

Database for which you want to create the index.

<collectionName>

Collection for which you want to create the index.

<indexName>

Name of your index. If you omit the index name, Atlas Search names the index default.

<IndexDefinition>

The definition of your index. To learn about index definition syntax, see Index Reference.

Replace the placeholder values in the following example application named create-index.js, which uses the createSearchIndexes command to define an Atlas Search index:

create-index.js
import { MongoClient } from "mongodb";
// connect to your Atlas deployment
const uri = "<connection-string>";
const client = new MongoClient(uri);
async function run() {
try {
const database = client.db("<databaseName>");
const collection = database.collection("<collectionName>");
// define an array of Atlas Search indexes
const indexes = [
{
name: "<first-index-name>",
definition: {
/* search index definition fields */
}
},
...
{
name: "<last-index-name>",
definition: {
/* search index definition fields */
}
}
]
// run the helper method
const result = await collection.createSearchIndexes(indexes);
console.log(result);
} finally {
await client.close();
}
}
run().catch(console.dir);
3

Use the following command:

node create-index.js
<index-name>

To use the Python Driver to create an Atlas Search index, define the search index from your application and call the create_search_index() method.

Note

The Atlas Search index management methods run asynchronously. The driver methods can return before confirming that they ran successfully. To determine the current status of the search indexes, call the list_search_indexes() method on your collection.

1
2

The following sample application defines a search index to dynamically index the fields in your collection. Then, the application calls the create_search_index() method on a collection to create the search index. To learn more, see Index Reference.

from pymongo.mongo_client import MongoClient
from pymongo.operations import SearchIndexModel
def create_index():
# Connect to your Atlas deployment
uri = "<connectionString>"
client = MongoClient(uri)
# Access your database and collection
database = client["<databaseName>"]
collection = database["<collectionName>"]
# Create your index model, then create the search index
search_index_model = SearchIndexModel(
definition={
"mappings": {
"dynamic": True
},
},
name="<indexName>",
)
result = collection.create_search_index(model=search_index_model)
print(result)

You can also create multiple Atlas Search indexes at once. In your application, define an array of search indexes. Then, pass the array as a parameter to the create_search_indexes() method:

from pymongo.mongo_client import MongoClient
from pymongo.operations import SearchIndexModel
def create_indexes():
# Connect to your Atlas deployment
uri = "<connectionString>"
client = MongoClient(uri)
# Access your database and collection
database = client["<databaseName>"]
collection = database["<collectionName>"]
# Create your index models and add them to an array
first_model = SearchIndexModel(
definition={
# Add search index definition fields here
},
name="<firstIndexName>",
)
second_model = SearchIndexModel(
definition={
# Add search index definition fields here
},
name="<secondIndexName>",
)
idx_models = [first_model, second_model]
# Create the search indexes
result = collection.create_search_indexes(models=idx_models)
print(result)
3
  • Your Atlas connection string. To learn more, see Connect via Drivers.

  • The database and collection for which you want to create the index.

  • The name of your index. If you omit the index name, Atlas Search names the index default.

4
python create_index.py

When you create the Atlas Search index, the Atlas Search page displays information about Atlas Search indexes. The Status column shows the current state of the index on the primary node of the cluster. To learn more, see Index Statuses.

Warning

If you shard a collection that already has an Atlas Search index, you might experience a brief period of query downtime when the collection begins to appear on a shard. Also, if you add a shard for an already sharded collection that contains an Atlas Search index, your search queries against that collection will fail until the initial sync process completes on the added shards. To learn more, see initial sync process.


Use the Select your language drop-down menu to set the language of the procedure in this section.


To list all search indexes for a cluster using the Atlas CLI, run the following command:

atlas clusters search indexes list [options]

To return the details for the search index you specify using the Atlas CLI, run the following command:

atlas clusters search indexes describe <indexId> [options]

To learn more about the syntax and parameters for the previous commands, see the Atlas CLI documentation for atlas clusters search indexes list and atlas clusters search indexes describe.

To describe the specified search index for the specified deployment using the Atlas CLI, run the following command:

atlas deployments search indexes describe [indexId] [options]

To list all search indexes for the specified deployment using the Atlas CLI, run the following command:

atlas deployments search indexes list [options]

To learn more about the syntax and parameters for the previous commands, see the Atlas CLI documentation for atlas deployments search indexes describe and atlas deployments search indexes list.

To retrieve an Atlas Search index using the Atlas Search API:

1

Send a GET request with either the unique ID or name of the Atlas Search index that you wish to retrieve to the search/indexes/ endpoint.

curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \ --header "Accept: application/json" \
--include \
--request GET "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId}"

To learn more about the syntax and parameters for either endpoint, see Get One By Name and Get One By ID.

2

To retrieve all Atlas Search indexes for a collection:

1

Send a GET request to the search/indexes/ endpoint with the name of the collection whose indexes you want to retrieve.

curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \ --header "Accept: application/json" \
--include \
--request GET "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{databaseName}/{collectionName}"
2

To retrieve all Atlas Search indexes for a cluster:

1

Send a GET request to the search/indexes/ endpoint with the name of the cluster whose indexes you want to retrieve.

curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \ --header "Accept: application/json" \
--include \
--request GET "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes"
2

To view the Atlas UI Atlas Search page:

1

Warning

Navigation Improvements In Progress

We're currently rolling out a new and improved navigation experience. If the following steps don't match your view in the Atlas UI, see the preview documentation.

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

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

  3. If it's not already displayed, click Clusters in the sidebar.

    The Clusters page displays.

2

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

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

    If you have no clusters, click Create cluster to create one. To learn more, see Create a Cluster.

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

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

The Atlas Search page contains a table that describes each of the existing Atlas Search indexes in your project in the following columns.

Column
Description

Database

Name of the database that contains the collection.

Collection

Name of the indexed collection.

Index Name

Name of the index.

Status

Status of the index on the primary node of the cluster. To learn more, see Atlas Search Index Statuses.

Queryable

Icon that identifies whether collection is queryable using the index. Value can be one of the following icons:

  • - for indexes that you can use to query the collection.

  • X - for indexes that you can't use to query the collection.

Type

Type of index. Value can be one of the following types of index:

Index Fields

Indexed fields. Value is dynamic if you enabled dynamic mappings. For static mappings, the column shows all of the indexed fields.

Documents

Approximate number and percentage of indexed documents out of the total number of documents in the collection during and after the index build on the primary or search node on the cluster.

Size

Size of the index.

Actions

Actions you can take on the index:

  • Click Query to go to the Search Tester for querying the collection.

  • Click and select one of the following actions to take on the index:

By default, Atlas sorts the indexes by first the database name and then the collection name. To sort by multiple columns, press Shift and click the column names in the order in which you want to multi-sort the list of indexes.

From this table, you can go to the following sections for more details about each index:

To go to the Index Overview page from the Atlas Search page, click the name of the index that you want to view in the Index Name column. For each index, the Index Overview page shows the namespace for the index and the following configurations specified in the index definition:

Row
Description

Index Analyzer

Chosen text analyzer that specifies how text is processed and tokenized when building the search index.

Search Analyzer

Chosen text analyzer that specifies how text in your search queries is processed and tokenized.

Dynamic Mapping

Boolean indicating whether or not you enabled dynamic or static mappings for your field mappings

Field Mappings

Any specified field mappings, including field name, data type, and whether dynamic mapping is enabled for the individual field

Stored Source Fields

Synonym Mappings

Any defined synonym mappings for word equivalents

The Status column on the Atlas Search page shows the current status of the index on the primary node of the cluster. The following table describes the possible index statuses:

Status
Description

Pending

Atlas has not yet started building the index.

Building

Atlas is building the index or re-building the index after an edit. When the index is in this state:

  • For a new index, Atlas Search doesn't serve queries until the index build is complete.

  • For an existing index, you can continue to use the old index for existing and new queries until the index rebuild is complete.

Ready

Index is ready to use.

Stale

Index is stale because of any of the following reasons:

  • Replication stopped due to high disk utilization.

    The pause replication threshold is 90% and the resume replication threshold is 85% disk utilization.

  • If replication stops for a long period, the Atlas Search mongot process falls off the oplog.

    This state commonly occurs when the current replication point is no longer available on the mongod oplog. Atlas rebuilds index if the mongot process falls of the oplog.

  • Index reached the two billion document limit.

  • Replication failed due to an error.

You can still query the existing index. However, the results for queries against a stale index might contain stale data. You can upscale your search nodes for more disk space and delete existing indexes to release disk space. Alternatively, use the error in the View status details modal window to troubleshoot the issue. To learn more, see Fix Atlas Search Issues.

Failed

Atlas could not build the index. Use the error in the View status details modal window to troubleshoot the issue. To learn more, see Fix Atlas Search Issues.

Deleting

Atlas is deleting the index from the cluster nodes.

Does not Exist

Index is invalid because the collection for the index no longer exists. You can't run queries on this index because there is no corresponding collection for this index. Atlas will eventually delete the index.

You can view more status information in the Status Details page in one of the following ways:

  • Click the View status details link in the Status column.

  • Click the name in the Index Name column then select Status Details from the menu on the left of the Index Overview.

The Status Details page contains the following sections:

This section displays the index that is being used to serve queries.

If you have only one version of the index with this name for the collection, the section contains a link to the Index Overview where you can see the index definition for the index being used.

If you had other indexes with the same name on the collection, the section shows the latest index definition and also shows prior valid versions of the index that you can copy in different tabs.

When you update an index, different nodes apply the updates at different speeds. Therefore, some nodes might use the latest version and some might use the prior version. Atlas displays both versions of the index until the changes are applied to all the nodes.

If you attempt to update the index with an invalid index definition, the index build will fail and Atlas displays only the previous valid index definition.

This section displays the status of the index on each node of the cluster. You can see the following details about the index on each node:

Shard

Shard name.

Node

Node information.

Status

Status of the index on the node in the shard.

Queryable

Icon that indicates whether the index can serve queries.

Message

Reason for the index status. For indexes in Stale or Failed state, displays the reason why the index is stale or why the index build failed.

Node Type

Type of node. Value can be one of the following types:

  • Primary

  • Secondary

  • Search Node

Region

Node region.

Size

Size of the index on the node.

Documents

Number and percentage of indexed documents.

Actions

Actions you can take on the index in the node. You can click the and select one of the following options:

This section displays the status of the in-progress migration of your Atlas Search and Atlas Vector Search indexes to search nodes, if applicable. This section displays only if you are currently migrating to search nodes.

Click the View Migration Progress link in the information banner under the Index Status by Search Node section for details on the progress of the migration of the indexes to Search Nodes (on a per node basis).

The Atlas UI displays the following columns for each index on the cluster.

Column
Description

Database

Name of the database that contains the collection.

Collection

Name of the indexed collection.

Index Name

Name of the index.

Index Fields

Indexed fields. Value is dynamic if you enabled dynamic mappings. For static mappings, the column shows all of the indexed fields.

Type

Type of index. Value can be one of the following types of index:

Status

Status of the migration. To learn more, see Migration to Search Nodes.

Size

Size of the index.

Documents

Number and percentage of indexed documents out of the total number of documents in the collection during and after the migration on the search nodes on the cluster.

The status column displays one of the following statuses of the index on the Search Nodes:

Status
Description

Building

The index is currently building on the Search Node. Your queries can continue to use existing indexes while the new index is building.

On Deck

The index is successfully built on the Search Nodes, but the migration is not yet complete. Note that migration is complete only when Atlas successfully builds all the indexes on the Search Nodes.

Ready

The index on the Search Node is ready for use in your queries. This displays only when Atlas successfully completes the migration to the Search Nodes.

Failed

The index build failed and the migration to separate Search Nodes is stalled. Your queries can continue to use the existing indexes. Atlas will try to rebuild the index, but will timeout after 7 days.

To migrate successfully, review error message for the index in the Status Details by Node Message column or in the Status Details page for the index and address issues that are causing the index build to fail on the Search Nodes.

Your queries can continue to use existing indexes while the new indexes are building on the Search Nodes. The migration to the Search Nodes completes only when Atlas successfully builds all the indexes on the Search Nodes. Then, your queries are automatically routed to the use the indexes on the Search Nodes.

To retrieve your Atlas Search indexes through mongosh, use the db.collection.getSearchIndexes() method.

The command has the following syntax. If you omit the index name, Atlas Search returns all indexes on the collection.

db.<collection>.getSearchIndexes("<index-name>")

The following command retrieves a search index named default from the movies collection. Your results should resemble the example output:

db.movies.getSearchIndexes("default")
[
{
id: '648b4ad4d697b73bf9d2e5e0',
name: 'default',
status: 'READY',
queryable: true,
latestDefinition: { mappings: { dynamic: true } }
}
]

To retrieve your Atlas Search indexes through the Node Driver, use the listSearchIndexes helper method.

You can use the following sample application named list-indexes.js to return the indexes on your collection. Specify the following values:

  • Your Atlas connection string. To learn more, see Connect via Drivers.

  • The database and collection that contains the search indexes that you want to retrieve.

  • The index name if you want to retrieve a specific index. To return all indexes on the collection, omit this value.

Note

The listSearchIndexes command returns a cursor. As a result, it doesn't immediately return the indexes matched by the command. To access the results, use a cursor paradigm such as the toArray() method. To learn more, see Access Data From a Cursor.

list-indexes.js
import { MongoClient } from "mongodb";
// connect to your Atlas deployment
const uri = "<connection-string>";
const client = new MongoClient(uri);
async function run() {
try {
const database = client.db("<databaseName>");
const collection = database.collection("<collectionName>");
// run the helper method
const result = await collection.listSearchIndexes("<index-name>").toArray();
console.log(result);
} finally {
await client.close();
}
}
run().catch(console.dir);

To run the sample application, use the following command. Your results should resemble the example output:

node list-indexes.js
[
{
id: '648b4ad4d697b73bf9d2e5e0',
name: 'default',
status: 'READY',
queryable: true,
latestDefinition: { mappings: { dynamic: true } }
},
{
id: '648b4ad4d697b73bf9d2e5e1',
name: 'example-index',
status: 'PENDING',
queryable: false,
latestDefinition: {
mappings: { dynamic: false, fields: { text: { type: 'string' } } }
}
}
]

To use the .NET/C# Driver to retrieve your Atlas Search indexes, use the List() or ListAsync() method.

The following sample application returns the indexes on a collection. Specify the following values:

  • Your Atlas connection string. To learn more, see Connect via Drivers.

  • The database and collection that contains the search indexes that you want to retrieve.

Note

The List() method returns a cursor instead of the indexes themselves. To access the indexes, use a cursor paradigm such as the MoveNext() method.

Program.cs
using MongoDB.Bson;
using MongoDB.Driver;
// connect to your Atlas deployment
var uri = "<connection-string>";
var client = new MongoClient(uri);
var db = client.GetDatabase("<databaseName>");
var collection = db.GetCollection<BsonDocument>("<collectionName>");
// list your Atlas Search indexes
var result = collection.SearchIndexes.List().ToList();
foreach (var index in result)
{
Console.WriteLine(index);
}

To run the sample application, create a new .NET console project named csharp-list-indexes and copy the previous code example into the Program.cs file. Then, use the following command to run the project:

dotnet run csharp-list-indexes.csproj
<indexes for this collection>

Tip

API Documentation

To learn more about the methods on this page, see the API documentation for the .NET/C# driver.

To retrieve Atlas Search indexes on a collection using the Java Driver, use the listSearchIndexes() method. You must have Java Driver v4.11.0 or higher.

1
2

The following sample application retrieves all Atlas Search indexes on a given collection.

1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoCursor;
5import com.mongodb.client.MongoDatabase;
6import org.bson.Document;
7public class ViewIndex {
8 public static void main(String[] args) {
9 // connect to your Atlas cluster
10 String uri = "<connection-string>";
11 try (MongoClient mongoClient = MongoClients.create(uri)) {
12 // set namespace
13 MongoDatabase database = mongoClient.getDatabase("<database-name>");
14 MongoCollection<Document> collection = database.getCollection("<collection-name>");
15 // retrieve indexes
16 try (MongoCursor<Document> resultsCursor = collection.listSearchIndexes().iterator()) {
17 while (resultsCursor.hasNext()) {
18 System.out.println(resultsCursor.next());
19 }
20 }
21 }
22 }
23}
3
  • <connection-string> - Your Atlas connection string. To learn more, see Connect via Drivers.

  • <database-name> - The name of the database that contains the collection.

  • <collection-name> - The name of the collection for which you want to retrieve the index.

4
javac ViewIndex.java
java ViewIndex

See also:

To use the C++ Driver to retrieve your Atlas Search indexes, call the list() method on a search index view.

1
2

The following sample application uses the search_indexes() method on the target collection to instantiate a search index view. Then, the application calls the list() method on the view. This method returns a cursor from which the code accesses and prints each Atlas Search index.

#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/search_index_view.hpp>
using namespace mongocxx;
int main()
{
mongocxx::instance instance{};
try
{
// Connect to your Atlas deployment
mongocxx::uri uri("<connectionString>");
mongocxx::client client(uri);
// Access your database and collection
auto db = client["<databaseName>"];
auto collection = db["<collectionName>"];
// Access and print the indexes in your collection
auto siv = collection.search_indexes();
auto cursor = siv.list();
for (auto&& doc : cursor) {
std::cout << bsoncxx::to_json(doc) << std::endl;
};
}
catch (const std::exception& e)
{
std::cout<< "Exception: " << e.what() << std::endl;
}
return 0;
}
3
  • Your Atlas connection string. To learn more, see Connect via Drivers.

  • The database and collection for which you want to retrieve the indexes.

4
g++ -o view-index view-index.cpp $(pkg-config --cflags --libs libmongocxx)
./view-index

To use the C Driver to retrieve your Atlas Search indexes, use the mongoc_collection_aggregate() method to create an aggregation pipeline that includes the $listSearchIndexes stage.

1
2

The following sample application specifies the $listSearchIndexes stage in an aggregation pipeline. Then, the application passes the pipeline and the target collection to the mongoc_collection_aggregate() method. This method returns a cursor from which the code accesses and prints each Atlas Search index:

#include <mongoc/mongoc.h>
#include <stdlib.h>
int main (void)
{
mongoc_client_t *client = NULL;
mongoc_collection_t *collection = NULL;
mongoc_database_t *database = NULL;
bson_error_t error;
bson_t cmd = BSON_INITIALIZER;
bool ok = true;
bson_t pipeline = BSON_INITIALIZER;
mongoc_cursor_t *cursor = NULL;
mongoc_init();
// Connect to your Atlas deployment
client = mongoc_client_new("<connectionString>");
if (!client) {
fprintf(stderr, "Failed to create a MongoDB client.\n");
ok = false;
goto cleanup;
}
// Access your database and collection
database = mongoc_client_get_database(client, "<databaseName>");
collection = mongoc_database_get_collection(database, "<collectionName>");
// Create an aggregation pipeline with the $listSearchIndexes stage
const char *pipeline_str =
BSON_STR ({"pipeline" : [ {"$listSearchIndexes" : {}} ]});
// Convert your aggregation pipeline to BSON
if (!bson_init_from_json(&pipeline, pipeline_str, -1, &error)) {
fprintf(stderr, "Failed to parse command: %s\n", error.message);
ok = false;
goto cleanup;
}
// Run the aggregation operation and iterate through the indexes returned
cursor = mongoc_collection_aggregate (collection,
MONGOC_QUERY_NONE,
&pipeline,
NULL,
NULL);
const bson_t *got;
char *str;
while (mongoc_cursor_next (cursor, &got)) {
str = bson_as_canonical_extended_json (got, NULL);
printf ("%s\n", str);
bson_free (str);
}
if (mongoc_cursor_error (cursor, &error)) {
fprintf (stderr, "Failed to iterate all documents: %s\n", error.message);
ok = false;
goto cleanup;
}
cleanup:
mongoc_cursor_destroy(cursor);
mongoc_collection_destroy(collection);
mongoc_database_destroy(database);
mongoc_client_destroy(client);
bson_destroy(&pipeline);
bson_destroy(&cmd);
mongoc_cleanup ();
return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}
3
  • Your Atlas connection string. To learn more, see Connect via Drivers.

  • The database and collection for which you want to retrieve the indexes.

4
gcc -o view-index view-index.c $(pkg-config --libs --cflags libmongoc-1.0)
./view-index

To use the Python Driver to retrieve your Atlas Search indexes, call the list_search_indexes() method on your collection.

1
2

The following sample application calls the list_search_indexes() method on a collection. This method returns a cursor from which the code accesses and prints each Atlas Search index:

from pymongo.mongo_client import MongoClient
def view_index():
# Connect to your Atlas deployment
uri = "<connectionString>"
client = MongoClient(uri)
# Access your database and collection
database = client["<databaseName>"]
collection = database["<collectionName>"]
# Get a list of the collection's search indexes and print them
cursor = collection.list_search_indexes()
for index in cursor:
print(index)
3
  • Your Atlas connection string. To learn more, see Connect via Drivers.

  • The database and collection for which you want to retrieve the indexes.

4
python view_index.py

To resume or delete your index definition that you saved as a draft in the Atlas UI:

Important

You can't create a new index when you have a pending index draft.

1

Warning

Navigation Improvements In Progress

We're currently rolling out a new and improved navigation experience. If the following steps don't match your view in the Atlas UI, see the preview documentation.

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

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

  3. If it's not already displayed, click Clusters in the sidebar.

    The Clusters page displays.

2

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

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

    If you have no clusters, click Create cluster to create one. To learn more, see Create a Cluster.

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

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3
4
  1. Click Cancel.

  2. Click Save Draft or Delete Draft.

5
  1. Click Refine Your Index to make changes to your index configuration.

  2. Click Save Changes.

6

Atlas displays a Toast (brief, non-interactive notification) to let you know your index is building.

7

The newly created index appears on the Atlas Search tab. While the index is building, the Status field reads Build in Progress. When the index is finished building, the Status field reads Active.

Note

Larger collections take longer to index. You will receive an email notification when your index is finished building.

You can change the index definition of an existing Atlas Search index. You cannot rename an index; if you need to change an index's name, you must create a new index and delete the old one.

You can edit an Atlas Search index in the Atlas UI, or programmatically by using mongosh, the Atlas CLI, the API, or a supported MongoDB Driver in your preferred language.


Use the Select your language drop-down menu to set the language of the procedure in this section.


To edit an Atlas Search index through the API:

1

Send a PATCH request with either the unique ID or name of the Atlas Search index that you wish to modify to the search/indexes/ endpoint.

curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
--header "Accept: application/json" \
--header "Content-Type: application/json" \
--include \
--request PATCH "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId}" \
--data '
{
"definition":
{
"analyzer": "lucene.<analyzer>",
"analyzers": [
{
"charFilters": [ ... ],
"name": "string",
"tokenFilters": [ ... ],
"tokenizer": { ... }
}
],
"mappings": {
"dynamic": true | false,
"fields": {
"property1": {},
...
}
},
"searchAnalyzer": "<analyzer-name>",
"storedSource": {
"include | exclude": [...]
},
"synonyms": [
{
<synonym-mapping-definition>
}
}
]
}
}'

To learn more about the syntax and parameters for either endpoint, see Update One By Name and Update One By ID.

2

To update a search index for a cluster using the Atlas CLI, run the following command:

atlas clusters search indexes update <indexId> [options]

To learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas clusters search indexes update.

1

Warning

Navigation Improvements In Progress

We're currently rolling out a new and improved navigation experience. If the following steps don't match your view in the Atlas UI, see the preview documentation.

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

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

  3. If it's not already displayed, click Clusters in the sidebar.

    The Clusters page displays.

2

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

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

    If you have no clusters, click Create cluster to create one. To learn more, see Create a Cluster.

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

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3
  • Edit With Visual Editor for a guided experience.

  • Edit With JSON Editor to edit the raw index definition.

4

Review the following index configuration settings:

Visual Editor Field
Description
Necessity

Index Analyzer

Specify the analyzer to use for indexing the collection data. By default, Atlas Search uses the standard analyzer (lucene.standard).

Corresponds to the analyzer JSON setting.

Optional

Search Analyzer

Specifies the analyzer to apply to query text before searching the text. If you omit this field, the index inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

Corresponds to the searchAnalyzer JSON setting.

Optional

Dynamic Mapping

Specify dynamic or static mapping of fields.

By default, dynamic mapping is enabled. To disable dynamic mapping, set dynamic to Off. If you disable dynamic mapping, you must specify the fields to index.

To learn more about dynamic and static mappings, see Define Field Mappings.

Corresponds to the mappings.dynamic JSON setting.

Required

Review the following advanced configuration settings:

Field Name
Description
Necessity

Field Mappings

Required if Dynamic Mapping in the Index Configurations section is disabled.

Specify the fields to index:

  1. Click Add Field Mapping to open the Add Field Mapping window.

  2. Specify the following information about the field:

    • Field name - Name of the field to index.

    • Data Type - Field data type. To learn more about the supported data types and their options, see Data Types.

  3. (Optional) Specify additional properties.

    A table of additional configuration options appears in the Add Field Mapping window. These properties depend on the data type that you selected in the last step.

    To learn more about the supported data types and their options, see Data Types.

  4. (Optional) Add multi field.

    Click Add Multi Field to configure an alternative field analyzer with which to index the field. To learn more, see Multi Analyzer.

  5. Click Add to add the field.

    You can click the ellipses (...) icon for the field in the Actions column to do the following:

    • Click Edit to modify the configuration.

    • Click Add Data Type to configure additional data types for the field.

    • Click Delete to remove the field from the index.

To learn more about defining field mappings, see Index Reference.

Corresponds to the mappings.fields JSON setting.

Conditional

Stored Source Fields

Specify the fields to store on Atlas Search for query-time lookups. You can store fields of all supported Data Types on Atlas Search.

To learn more about storing fields, see Define Stored Source Fields in Your Atlas Search Index.

Corresponds to the storedSource JSON setting.

Optional

Synonyms Mappings

Specify synonym mappings to use in your index.

You can use a synonym mapping to query only fields analyzed with the same analyzer.

To learn more about synonym mappings, see Define Synonym Mappings in Your Atlas Search Index.

Corresponds to the synonyms JSON setting.

Optional.

Index Partitions

The number of partitions to use if field objects exceed 2.1 billion.

Corresponds to the numPartitions JSON setting.

Optional.

Review the following index configuration settings:

Field Name
Description
Necessity

analyzer

Specify the analyzer to use for indexing the collection data. By default, Atlas Search uses the standard analyzer (lucene.standard).

Optional

searchAnalyzer

Specifies the analyzer to apply to query text before searching the text. If you omit this field, the index inherits an analyzer by default in the following order:

  1. The analyzer option for this field if specified.

  2. The searchAnalyzer option for the index if specified.

  3. The analyzer option for the index if specified.

  4. The lucene.standard analyzer.

Optional

mappings.dynamic

Specify dynamic or static mapping of fields. To disable dynamic mapping, set "dynamic": to false. By default, dynamic mapping is enabled. If you disable dynamic mapping, you must specify the fields to index. To learn more about dynamic and static mappings, see Index Reference.

Required

Review the following advanced configuration settings:

Field Name
Description
Necessity

mappings.fields

Required if mappings.dynamic is false.

Specify the fields that you would like to index. To learn more, see Define Field Mappings.

Conditional

storedSource

Specify the fields to store on Atlas Search for query-time lookups. You can store fields of all supported Data Types on Atlas Search.

To learn more about storing fields, see Define Stored Source Fields in Your Atlas Search Index.

Optional

synonyms

Specify synonym mappings to use in your index.

You can use a synonym mapping to query only fields analyzed with the same analyzer.

To learn more about synonym mappings, see Define Synonym Mappings in Your Atlas Search Index.

Optional

numPartitions

The number of partitions to use if field objects exceed 2.1 billion.

Optional.

To learn more about these index definition settings, see Index Reference.

5

The index's status changes from Active to Building. In this state, you can continue to use the old index because Atlas Search does not delete the old index until the updated index is ready for use. Once the status returns to Active, the modified index is ready to use.

To edit an Atlas Search index through mongosh, use the db.collection.updateSearchIndex() method.

The command has the following syntax. Specify the name of the index that you want to edit and define the new index definition. This definition replaces the index's existing definition. To learn more, see Index Reference.

db.<collection>.updateSearchIndex(
"<index-name>",
/* updated search index definition */
)

The following command updates a search index named default from the movies collection to use static mappings:

db.movies.updateSearchIndex(
"default",
{
"mappings": {
"dynamic": false,
"fields": {
"<field-name>": {
"type": "<field-type>"
}
}
}
)

Note

The db.collection.updateSearchIndex() command doesn't return an output. You can use the Atlas UI to view the index status.

To edit an Atlas Search index using MongoDB Compass:

1
2
3
4

To use the C Driver to edit your Atlas Search indexes, specify the updated index information in your application and call the mongoc_collection_command_simple() method.

1
2

The following sample application specifies the updateSearchIndex command, an updated index definition, and an existing index name. Then, the application converts the command and updated index information to BSON and passes this information to the mongoc_collection_command_simple() method to edit the search index.

#include <mongoc/mongoc.h>
#include <stdlib.h>
int main (void)
{
mongoc_client_t *client = NULL;
mongoc_collection_t *collection = NULL;
mongoc_database_t *database = NULL;
bson_error_t error;
bson_t cmd = BSON_INITIALIZER;
bool ok = true;
mongoc_init();
// Connect to your Atlas deployment
client = mongoc_client_new("<connectionString>");
if (!client) {
fprintf(stderr, "Failed to create a MongoDB client.\n");
ok = false;
goto cleanup;
}
// Access your database and collection
database = mongoc_client_get_database(client, "<databaseName>");
collection = mongoc_database_get_collection(database, "<collectionName>");
// Specify the command and the updated index definition
const char *cmd_str = BSON_STR({
"updateSearchIndex" : "<collectionName>",
"definition" : {"mappings" : {"dynamic" : true}},
"name" : "<indexName>"
});
// Convert your command to BSON
if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) {
fprintf(stderr, "Failed to parse command: %s\n", error.message);
ok = false;
goto cleanup;
}
// Update the Atlas search index by running the command
if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) {
fprintf(stderr, "Failed to run updateSearchIndex: %s\n", error.message);
ok = false;
goto cleanup;
}
printf ("Index updated!\n");
cleanup:
mongoc_collection_destroy (collection);
mongoc_database_destroy (database);
mongoc_client_destroy (client);
bson_destroy (&cmd);
mongoc_cleanup ();
return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}
3
  • Your Atlas connection string. To learn more, see Connect via Drivers.

  • The database and collection for which you want to update an index.

  • The name of the index that you want to update.

  • The fields to redefine your search index. To learn more, see Index Reference.

4
gcc -o edit-index edit-index.c $(pkg-config --libs --cflags libmongoc-1.0)
./edit-index

To use the C++ Driver to edit an Atlas Search index, call the update_one() method on a search index view.

1
2

The following sample application instantiates a search index view and specifies a new Atlas Search index definition. Then, the application passes this definition and an existing index name to the update_one() method, which updates the existing index to reflect the new definition document.

#include <bsoncxx/builder/basic/document.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/search_index_view.hpp>
using namespace mongocxx;
using bsoncxx::builder::basic::make_document;
int main()
{
mongocxx::instance instance{};
try
{
// Connect to your Atlas deployment
mongocxx::uri uri("<connectionString>");
mongocxx::client client(uri);
// Access your database and collection
auto db = client["<databaseName>"];
auto collection = db["<collectionName>"];
// Access the indexes in your collection
auto siv = collection.search_indexes();
// Specify a new definiton and update your search index
auto newDefinition = make_document(kvp("mappings", make_document(kvp("dynamic", true))));
siv.update_one("<indexName>", newDefinition.view());
}
catch (const std::exception& e)
{
std::cout<< "Exception: " << e.what() << std::endl;
}
return 0;
}
3
  • Your Atlas connection string. To learn more, see Connect via Drivers.

  • The database and collection for which you want to update an index.

  • The name of the index that you want to update.

  • The fields to redefine your search index. To learn more, see Index Reference.

4
g++ -o edit-index edit-index.cpp $(pkg-config --cflags --libs libmongocxx)
./edit-index

To use the .NET/C# Driver to edit an Atlas Search index, use the Update() or UpdateAsync() method.

The following sample application updates an existing index definition. Specify the following values:

  • Your Atlas connection string. To learn more, see Connect via Drivers.

  • The database and collection where you created the search index.

  • The new index definition to replace the existing definition. In the example, you update an index to use static mappings. You can alter this definition to suit your specific indexing needs. To learn more, see Index Reference.

  • The name of the index that you want to update.

Program.cs
using MongoDB.Bson;
using MongoDB.Driver;
// connect to your Atlas deployment
var uri = "<connection-string>";
var client = new MongoClient(uri);
var db = client.GetDatabase("<databaseName>");
var collection = db.GetCollection<BsonDocument>("<collectionName>");
// define your Atlas Search index
var index = new BsonDocument
{
// updated search index definition
{ "mappings", new BsonDocument
{
{ "dynamic", false },
{ "fields", new BsonDocument
{
{ "<field-name>", new BsonDocument
{
{ "type", "<field-type>" }
}
}
}
}
}
}
};
collection.SearchIndexes.Update("<index-name>", index);

To run the sample application, create a new .NET console project named csharp-update-index and copy the previous code example into the Program.cs file. Then, use the following command to run the project:

dotnet run csharp-update-index.csproj

Note

The Update() method doesn't return an output. You can use the Atlas UI to view the index status.

Tip

API Documentation

To learn more about the methods on this page, see the API documentation for the .NET/C# driver.

To edit an Atlas Search index on a collection using the Java Driver, construct a document that modifies the search index settings, and then pass the document to the updateSearchIndex() method. You must have Java Driver v4.11.0 or higher.

1
2
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6
7public class EditIndex {
8 public static void main(String[] args) {
9 // connect to your Atlas cluster
10 String uri = "<connection-string>";
11
12 try (MongoClient mongoClient = MongoClients.create(uri)) {
13 // set namespace
14 MongoDatabase database = mongoClient.getDatabase("<document-name>");
15 MongoCollection<Document> collection = database.getCollection("<collection-name>");
16 // define field mappings
17 Document index = new Document("analyzer", "<analyzer-name>").append(
18 "mappings", new Document("dynamic", <true|false>)
19 .append("fields", new Document("<field-name>",
20 new Document("type", "<field-type>"))));
21 // run the updateSearchIndex() method
22 collection.updateSearchIndex("<index-name>", index);
23 }
24 }
25}
3
  • <connection-string> - Your Atlas connection string. To learn more, see Connect via Drivers.

    Note

    In your connection string, don't include the writeConcern setting.

  • <database-name> - The name of the database that contains the collection.

  • <collection-name> - The name of the collection for which you want to retrieve the index.

  • <analyzer-name> - The name of the analyzer.

  • dynamic - The flag that indicates whether or not to automatically index the fields.

  • <field-name> - The name of the field to index.

  • <field-type> - The field data type.

  • <index-name> - The name of the index.

4
javac EditIndex.java
java EditIndex

The updateSearchIndex() method runs asynchronously. Use the listSearchIndexes() method to determine if the changes have been applied to your index. To learn more about retrieving Atlas Search indexes, see View Atlas Search Indexes.

See also:

To edit an Atlas Search index through the Node Driver, use the updateSearchIndex helper method.

You can use the following sample application named update-index.js to update an existing index definition. Specify the following values:

  • Your Atlas connection string. To learn more, see Connect via Drivers.

  • The database and collection where you created the search index.

  • The new index definition to replace the existing definition. In the example, you update an index to use static mappings. You can alter this definition to suit your specific indexing needs. To learn more, see Index Reference.

  • The name of the index that you want to update.

update-index.js
import { MongoClient } from "mongodb";
// connect to your Atlas deployment
const uri = "<connection-string>";
const client = new MongoClient(uri);
async function run() {
try {
const database = client.db("<databaseName>");
const collection = database.collection("<collectionName>");
// define your Atlas Search index
const index = {
/* updated search index definition */
"mappings": {
"dynamic": false,
"fields": {
"<field-name>": {
"type": "<field-type>"
}
}
}
}
// run the helper method
await collection.updateSearchIndex("<index-name>", index);
} finally {
await client.close();
}
}
run().catch(console.dir);

To run the sample application, use the following command:

node update-index.js

Note

The updateSearchIndex method doesn't return an output. You can use the Atlas UI to view the index status.

To use the Python Driver to update your Atlas Search indexes, call the update_search_index() method on your collection.

1
2

The following sample application specifies a new Atlas Search index definition. Then, the application passes this definition and an existing index name to the update_search_index() method, which updates the existing index to reflect the new definition document.

from pymongo.mongo_client import MongoClient
def edit_index():
# Connect to your Atlas deployment
uri = "<connectionString>"
client = MongoClient(uri)
# Access your database and collection
database = client["<databaseName>"]
collection = database["<collectionName>"]
# Specify a new index definition
definition = {
"mappings": {
"dynamic": True
},
}
# Update your search index
collection.update_search_index("<indexName>", definition)
3
  • Your Atlas connection string. To learn more, see Connect via Drivers.

  • The database and collection for which you want to update an index.

  • The name of the index that you want to update.

  • The fields to redefine your search index. To learn more, see Index Reference.

4
python edit_index.py

Note

While your updated index is building, different nodes may update at varying speeds. During this period, you may experience mixed query results, reflecting both the new index definition and the previous index definition. You can view the index that is serving queries in the index status details page.

Some Atlas Search features require that you update the index. To update your index, you can take one of the following actions:

  • Edit the index definition using the steps in Edit an Atlas Search Index.

  • Do the following steps to opt-in for an index update from the Atlas UI:

Important

The process for updating the Atlas Search index requires time and resources. For the index update to complete successfully, allocate free disk space equal to 125% of your current index's disk space.

1

Warning

Navigation Improvements In Progress

We're currently rolling out a new and improved navigation experience. If the following steps don't match your view in the Atlas UI, see the preview documentation.

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

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

  3. If it's not already displayed, click Clusters in the sidebar.

    The Clusters page displays.

2

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

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

    If you have no clusters, click Create cluster to create one. To learn more, see Create a Cluster.

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

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3

Tip

If an index requires an update to enable a new feature, the Atlas UI shows a warning icon next to the index name.

4
  1. In the Index Overview page, click Update in the banner.

  2. Click Update Index in the confirmation window.

    While your index is updating, you can continue to query your collection using your previous index.

You can delete an Atlas Search index in the Atlas UI, or programmatically by using mongosh, the Atlas CLI, the API, or a supported MongoDB Driver in your preferred language.


Use the Select your language drop-down menu to set the language of the procedure in this section.


To delete an Atlas Search index through the API:

1

Send a DELETE request with either the unique ID or name of the Atlas Search index that you wish to delete to the search/indexes/ endpoint.

curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \ --header "Accept: application/json" \
--include \
--request DELETE "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId}"

To learn more about the syntax and parameters for either endpoint, see Delete One By Name and Delete One By ID.

2

To delete a search index from a cluster using the Atlas CLI, run the following command:

atlas clusters search indexes delete <indexId> [options]

To learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas clusters search indexes delete.

To delete the specified search index for the specified deployment using the Atlas CLI, run the following command:

atlas deployments search indexes delete <indexId> [options]

To learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas deployments search indexes delete.

1

Warning

Navigation Improvements In Progress

We're currently rolling out a new and improved navigation experience. If the following steps don't match your view in the Atlas UI, see the preview documentation.

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

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

  3. If it's not already displayed, click Clusters in the sidebar.

    The Clusters page displays.

2

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

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

    If you have no clusters, click Create cluster to create one. To learn more, see Create a Cluster.

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

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3

The ellipsis button is located on the right side of the panel. Click the button beside your desired index and select Delete Index.

4

To delete an Atlas Search index through mongosh, use the db.collection.dropSearchIndex() method.

The command has the following syntax:

db.<collection>.dropSearchIndex("<index-name>")

The following command deletes a search index named default from the movies collection:

db.movies.dropSearchIndex("default")

Note

The db.collection.dropSearchIndex() command doesn't return an output. You can use the Atlas UI to view the index status.

To delete an Atlas Search index using MongoDB Compass:

1
2
3
4

To use the C Driver to delete your Atlas Search index, pass your collection and the drop command to the mongoc_collection_command_simple() method.

1
2

The following sample application specifies the dropSearchIndex command and an existing index name. Then, the application converts the command and index information to BSON and passes this information to the mongoc_collection_command_simple() method to delete the search index.

#include <mongoc/mongoc.h>
#include <stdlib.h>
int main (void)
{
mongoc_client_t *client = NULL;
mongoc_collection_t *collection = NULL;
mongoc_database_t *database = NULL;
bson_error_t error;
bson_t cmd = BSON_INITIALIZER;
bool ok = true;
mongoc_init();
// Connect to your Atlas deployment
client = mongoc_client_new("<connectionString>");
if (!client) {
fprintf(stderr, "Failed to create a MongoDB client.\n");
ok = false;
goto cleanup;
}
// Access your database and collection
database = mongoc_client_get_database(client, "<databaseName>");
collection = mongoc_database_get_collection(database, "<collectionName>");
// Specify the command and the index name
const char *cmd_str =
BSON_STR ({"dropSearchIndex" : "<collectionName>", "name" : "<indexName>"});
// Convert your command to BSON
if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) {
fprintf(stderr, "Failed to parse command: %s\n", error.message);
ok = false;
goto cleanup;
}
// Run the command to drop the search index
if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) {
fprintf(stderr, "Failed to run dropSearchIndex: %s\n", error.message);
ok = false;
goto cleanup;
}
printf ("Index dropped!\n");
cleanup:
mongoc_collection_destroy(collection);
mongoc_database_destroy(database);
mongoc_client_destroy(client);
bson_destroy(&cmd);
mongoc_cleanup ();
return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}
3
  • Your Atlas connection string. To learn more, see Connect via Drivers.

  • The database and collection for which you want to delete an index.

  • The name of the index that you want to delete.

4
gcc -o delete-index delete-index.c $(pkg-config --libs --cflags libmongoc-1.0)
./delete-index

To use the C++ Driver to delete your Atlas Search index, call the drop_one() method on a search index view.

1
2

The following sample application uses the search_indexes() method on the target collection to instantiate a search index view. Then, the application calls the drop_one() method on the view and passes an Atlas Search index name as a parameter to delete the index.

#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/search_index_view.hpp>
using namespace mongocxx;
int main()
{
mongocxx::instance instance{};
try
{
// Connect to your Atlas deployment
mongocxx::uri uri("<connectionString>");
mongocxx::client client(uri);
// Access your database and collection
auto db = client["<databaseName>"];
auto collection = db["<collectionName>"];
// Access the indexes in your collection
auto siv = collection.search_indexes();
// Delete your search index
auto name = "<indexName>";
siv.drop_one(name);
}
catch (const std::exception& e)
{
std::cout<< "Exception: " << e.what() << std::endl;
}
return 0;
}
3
  • Your Atlas connection string. To learn more, see Connect via Drivers.

  • The database and collection for which you want to retrieve the indexes.

  • The name of the index that you want to delete.

4
g++ -o delete-index delete-index.cpp $(pkg-config --cflags --libs libmongocxx)
./delete-index

To use the .NET/C# Driver to delete an Atlas Search index, use the DropOne() or DropOneAsync() method.

The following sample application deletes an index from a collection. Specify the following values:

  • Your Atlas connection string. To learn more, see Connect via Drivers.

  • The database and collection that contains the search index that you want to delete.

  • The name of the search index that you want to delete.

Program.cs
using MongoDB.Bson;
using MongoDB.Driver;
// connect to your Atlas deployment
var uri = "<connection-string>";
var client = new MongoClient(uri);
var db = client.GetDatabase("<databaseName>");
var collection = db.GetCollection<BsonDocument>("<collectionName>");
// drop your Atlas Search index
collection.SearchIndexes.DropOne("<index name>");

To run the sample application, create a new .NET console project named csharp-delete-index and copy the previous code example into the Program.cs file. Then, use the following command to run the project:

dotnet run csharp-delete-index.csproj

Note

The DropOne() method doesn't return an output. You can use the Atlas UI to view the index status.

Tip

API Documentation

To learn more about the methods on this page, see the API documentation for the .NET/C# driver.

To delete an Atlas Search index on a collection using the Java Driver, use the dropSearchIndex() method. You must have Java Driver v4.11.0 or higher.

1
2

The following sample application deletes the specified Atlas Search index on the specified collection.

1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6
7public class DeleteIndex {
8 public static void main(String[] args) {
9 // connect to your Atlas cluster
10 String uri = "<connection-string>";
11
12 try (MongoClient mongoClient = MongoClients.create(uri)) {
13 // set namespace
14 MongoDatabase database = mongoClient.getDatabase("<database-name>");
15 MongoCollection<Document> collection = database.getCollection("<collection>");
16 // delete the index
17 collection.dropSearchIndex("<index-name>");
18 }
19 }
20}
3
  • <connection-string> - Your Atlas connection string. To learn more, see Connect via Drivers.

    Note

    In your connection string, don't include the writeConcern setting.

  • <database-name> - The name of the database that contains the collection.

  • <collection-name> - The name of the collection for which you want to retrieve the index.

  • <index-name> - the name of the index to delete.

4
javac DeleteIndex.java
java DeleteIndex

See also:

To delete an Atlas Search index through the Node Driver, use the dropSearchIndex helper method.

You can use the following sample application named drop-index.js to delete an index on your collection. Specify the following values:

  • Your Atlas connection string. To learn more, see Connect via Drivers.

  • The database and collection where you created the search index.

  • The name of the index that you want to delete.

drop-index.js
// connect to your Atlas deployment
const uri = "<connection-string>";
const client = new MongoClient(uri);
async function run() {
try {
const database = client.db("<databaseName>");
const collection = database.collection("<collectionName>");
// run the helper method
await collection.dropSearchIndex("<index-name>");
} finally {
await client.close();
}
}
run().catch(console.dir);

To run the sample application, use the following command.

node drop-index.js

Note

The dropSearchIndex method doesn't return an output. You can use the Atlas UI to view the index status.

To use the Python Driver to delete your Atlas Search index, call the drop_search_index() method on your collection.

1
2

The following sample application passes an Atlas Search index name to the drop_search_index() method to delete the index.

from pymongo.mongo_client import MongoClient
def delete_index():
# Connect to your Atlas deployment
uri = "<connectionString>"
client = MongoClient(uri)
# Access your database and collection
database = client["<databaseName>"]
collection = database["<collectionName>"]
# Delete your search index
collection.drop_search_index("<indexName>")
3
  • Your Atlas connection string. To learn more, see Connect via Drivers.

  • The database and collection for which you want to delete an index.

  • The name of the index that you want to delete.

4
python delete_index.py

The mongot process stores the indexed fields and the _id field on disk, so you may want to adjust the size of your index before you build it. You can estimate the size of your full Atlas Search index by creating an index on a subset of your collection and scaling the size of the sample data index based on the total size of your data using the following formula:

estimated-index-size = ( subset-data-index-size / subset-data-size ) x total-collection-data-size

For example, if you want to estimate the size of an index for the movies collection in the sample_mflix database, perform the following steps in mongosh:

  1. Run $sample to create a new collection called sample_data using a random sample of your data:

    use sample_mflix
    db.movies.aggregate([
    { $sample: { size: 10 } },
    { $out: "sample_data" }
    ])
    [
    {
    _id: ObjectId('573a13bbf29313caabd53f9c'),
    plot: "Three years ago, in real-life, Hama Ali, a charismatic actor from Iraq famous locally for his performance as Iraq's version of Superman, met Ayca on a film-set. He and Ayca, a fiery actress...",
    genres: [ 'Drama', 'Romance', 'War' ],
    runtime: 93,
    cast: [
    'Ayèa Damgaci',
    'Hama Ali Kahn',
    'Cengiz Bozkurt',
    'Nesrin Cavadzade'
    ],
    num_mflix_comments: 1,
    poster: 'https://m.media-amazon.com/images/M/MV5BMjA1OTI1MjI4OV5BMl5BanBnXkFtZTgwODk1MTA2MDE@._V1_SY1000_SX677_AL_.jpg',
    title: 'Gitmek: My Marlon and Brando',
    fullplot: "Three years ago, in real-life, Hama Ali, a charismatic actor from Iraq famous locally for his performance as Iraq's version of Superman, met Ayca on a film-set. He and Ayca, a fiery actress from Turkey, had a passionate love affair before returning to their respective homes. From his Kurdish village, Hama Ali sends Ayca video love letters which he has filmed on his handycam. She watches them from her sofa in Istanbul, with her cat for company. The video love letters capture the hellish violence engulfing Iraq, the goats and uncles populating his rural area, and also his tender affection towards her. Feeling suffocated by her own city and angered by the indifference towards the war that surrounds her, Ayca decides to make the journey eastwards to Iraq to be reunited with her lover. GITMEK, a dramatic feature film, is based on the true story of Ayca's departure from Istanbul and her extraordinary journey to the Iraqi border. At a time when many people were fleeing from East to West in search of safety, Ayca makes the opposite journey, in search of love. She is helped by immigrant artists who live in the slums of Istanbul and the mothers of long distance truck drivers who she meets at various border towns. The journey takes her through breathtaking landscapes, strange encounters and terrifying times.",
    languages: [ 'English', 'Kurdish', 'Turkish' ],
    released: ISODate('2008-11-14T00:00:00.000Z'),
    directors: [ 'Huseyin Karabey' ],
    writers: [ 'Ayèa Damgaci', 'Huseyin Karabey' ],
    awards: { wins: 12, nominations: 4, text: '12 wins & 4 nominations.' },
    lastupdated: '2015-07-04 00:20:59.083000000',
    year: 2008,
    imdb: { rating: 6.6, votes: 628, id: 920460 },
    countries: [ 'Turkey' ],
    type: 'movie',
    tomatoes: {
    viewer: { rating: 3.7, numReviews: 181, meter: 79 },
    lastUpdated: ISODate('2015-07-16T18:10:38.000Z')
    }
    },
    {
    _id: ObjectId('573a139af29313caabcefb6a'),
    plot: '48 hours of intersecting lives and crimes in Los Angeles.',
    genres: [ 'Comedy', 'Crime', 'Drama' ],
    runtime: 104,
    rated: 'R',
    cast: [
    'Danny Aiello',
    'Greg Cruttwell',
    'Jeff Daniels',
    'Teri Hatcher'
    ],
    num_mflix_comments: 1,
    poster: 'https://m.media-amazon.com/images/M/MV5BZDI0ZmFmYTgtMTQ5OS00MTVmLTgwNWYtNzIyY2Y5NjYxNzgyXkEyXkFqcGdeQXVyNzc5MjA3OA@@._V1_SY1000_SX677_AL_.jpg',
    title: '2 Days in the Valley',
    fullplot: 'John Herzfeld deftly welds together a multitude of subplots-- a loser hitman and a cool assassin involved in an insurance scam; a washed-up director, turned suicidal, if only he had someone to care for his beloved dog; a snooty art dealer, wracked by kidney stones, cared for by his devoted assistant; a grungy deranged vice cop, now partnered with a fresh-faced rookie; and two beautiful and jealous women entangled in their deadly scheme--into a spoof of the crime thriller genre.',
    languages: [ 'English', 'Vietnamese' ],
    released: ISODate('1996-09-27T00:00:00.000Z'),
    directors: [ 'John Herzfeld' ],
    writers: [ 'John Herzfeld' ],
    awards: { wins: 0, nominations: 1, text: '1 nomination.' },
    lastupdated: '2015-09-11 00:42:22.520000000',
    year: 1996,
    imdb: { rating: 6.5, votes: 15019, id: 115438 },
    countries: [ 'USA' ],
    type: 'movie',
    tomatoes: {
    viewer: { rating: 3, numReviews: 14630, meter: 55 },
    dvd: ISODate('2001-08-07T00:00:00.000Z'),
    critic: { rating: 6, numReviews: 53, meter: 60 },
    lastUpdated: ISODate('2015-08-19T18:25:36.000Z'),
    consensus: 'A labyrinthine thriller with a host of memorable characters, 2 Days in the Valley is an uneven but intriguing thriller/black comedy.',
    rotten: 21,
    production: 'HBO Video',
    fresh: 32
    }
    },
    {
    _id: ObjectId('573a13bdf29313caabd5943e'),
    fullplot: "When Emily Parris exposes a secret society of teenage girls who have slipped out of the world of social media and into another world they've discovered in the woods at night. When she accuses the girls of committing sexually deviant activities, Emily sends the small American town into a atmosphere of hysteria and the national media spotlight. The mystery deepens when each of the accused girls upholds a vow of silence.",
    imdb: { rating: 6.2, votes: 861, id: 1015471 },
    year: 2014,
    plot: "When a teenage girl says she's the victim of a secret network called The Sisterhood of Night, a quiet suburban town becomes the backdrop for a modern-day Salem witch trial.",
    genres: [ 'Drama', 'Mystery', 'Thriller' ],
    rated: 'PG-13',
    metacritic: 60,
    title: 'The Sisterhood of Night',
    lastupdated: '2015-09-10 17:22:16.113000000',
    languages: [ 'English' ],
    writers: [ 'Marilyn Fu (screenplay)', 'Steven Millhauser (short story)' ],
    type: 'movie',
    tomatoes: {
    website: 'http://www.thesisterhoodofnight-movie.com/',
    viewer: { rating: 3.6, numReviews: 382, meter: 65 },
    dvd: ISODate('2015-06-09T00:00:00.000Z'),
    critic: { rating: 6.6, numReviews: 19, meter: 79 },
    boxOffice: '$5.3k',
    rotten: 4,
    production: 'Cine Mosaic',
    lastUpdated: ISODate('2015-09-13T17:24:37.000Z'),
    fresh: 15
    },
    poster: 'https://m.media-amazon.com/images/M/MV5BODg3MjE0MDM4N15BMl5BanBnXkFtZTgwOTY0MjE5NDE@._V1_SY1000_SX677_AL_.jpg',
    num_mflix_comments: 1,
    released: ISODate('2014-10-18T00:00:00.000Z'),
    awards: { wins: 2, nominations: 3, text: '2 wins & 3 nominations.' },
    countries: [ 'USA' ],
    cast: [
    'Georgie Henley',
    'Kara Hayward',
    'Willa Cuthrell',
    'Olivia DeJonge'
    ],
    directors: [ 'Caryn Waechter' ],
    runtime: 104
    },
    {
    _id: ObjectId('573a13c4f29313caabd6d7bf'),
    plot: 'A film producer struggles with suicidal despair.',
    genres: [ 'Drama' ],
    runtime: 110,
    metacritic: 76,
    cast: [
    'Louis-Do de Lencquesaing',
    'Chiara Caselli',
    'Alice de Lencquesaing',
    'Alice Gautier'
    ],
    num_mflix_comments: 0,
    poster: 'https://m.media-amazon.com/images/M/MV5BMTUxODczODA2NV5BMl5BanBnXkFtZTcwNzExMjQ1Mw@@._V1_SY1000_SX677_AL_.jpg',
    title: 'Father of My Children',
    fullplot: "In the first half, Gregoire, a movie producer of great charm, owner of Moon Films, plays with his younger daughters, talks with his wife and his eldest daughter, and keeps his studio going while one project hemorrhages money and creditors circle. In the second half, Sylvia, his Italian wife, tries to hold the family together as she looks fully into Moon Films' troubles. She meets with a banker, a temperamental Swede, Russian TV magnates, a film lab exec, and Moon's lawyer. Clèmence, the oldest daughter, goes on her own search. Debt can crush; how does a family pick up the pieces?",
    languages: [ 'French' ],
    released: ISODate('2009-12-16T00:00:00.000Z'),
    directors: [ 'Mia Hansen-Lève' ],
    writers: [ 'Mia Hansen-Lève (screenplay)' ],
    awards: { wins: 2, nominations: 3, text: '2 wins & 3 nominations.' },
    lastupdated: '2015-09-02 00:01:22.897000000',
    year: 2009,
    imdb: { rating: 6.7, votes: 1820, id: 1356928 },
    countries: [ 'France', 'Germany', 'Belgium' ],
    type: 'movie',
    tomatoes: {
    website: 'http://www.filmsdulosange.fr/fr/fr_peredemesenfants.html',
    viewer: { rating: 3.3, numReviews: 1232, meter: 60 },
    dvd: ISODate('2010-06-21T00:00:00.000Z'),
    critic: { rating: 7.4, numReviews: 55, meter: 91 },
    lastUpdated: ISODate('2015-09-11T18:38:12.000Z'),
    consensus: 'A tragedy gracefully lifted by tender empathy and moments of joy, Father of My Children is a quiet triumph for writer-director Mia Hansen-Love.',
    rotten: 5,
    production: 'IFC Films',
    fresh: 50
    }
    },
    {
    _id: ObjectId('573a13a5f29313caabd15cc1'),
    plot: 'After a 13-year imprisonment in Hong Kong, a kickboxer challenges the current champion in order to restore his honor.',
    genres: [ 'Drama', 'Romance', 'Sport' ],
    runtime: 105,
    cast: [
    'Andy Lau',
    'Takako Tokiwa',
    'Inthira Charoenpura',
    'Apichaya Thanatthanapong'
    ],
    title: 'Ah Fu',
    lastupdated: '2015-09-14 12:56:13.823000000',
    languages: [ 'Cantonese' ],
    released: ISODate('2000-11-21T00:00:00.000Z'),
    directors: [ 'Daniel Lee' ],
    writers: [ 'Chi-Sing Cheung', 'Daniel Lee' ],
    awards: { wins: 1, nominations: 3, text: '1 win & 3 nominations.' },
    year: 2000,
    imdb: { rating: 6.6, votes: 350, id: 277558 },
    countries: [ 'Hong Kong' ],
    type: 'movie',
    tomatoes: {
    viewer: { rating: 3.3, numReviews: 644, meter: 57 },
    lastUpdated: ISODate('2015-04-25T18:41:33.000Z')
    },
    num_mflix_comments: 0
    },
    {
    _id: ObjectId('573a13bef29313caabd5ce2b'),
    plot: 'Johann Sebastian Bach llega con su familia a Leipzig para ocupar el puesto de cantor en la Escuela de Santo Tomès...',
    genres: [ 'Musical' ],
    runtime: 102,
    metacritic: 70,
    cast: [
    'Christian Atanasiu',
    'Fèodor Atkine',
    'George-Christoph Biller',
    'Christian Brembeck'
    ],
    title: 'The Silence Before Bach',
    lastupdated: '2015-05-25 00:50:52.210000000',
    languages: [ 'Spanish', 'German', 'Catalan' ],
    released: ISODate('2007-12-21T00:00:00.000Z'),
    directors: [ 'Pere Portabella' ],
    writers: [ 'Xavier Albertè', 'Pere Portabella', 'Carles Santos' ],
    awards: { wins: 3, nominations: 3, text: '3 wins & 3 nominations.' },
    year: 2007,
    imdb: { rating: 6.8, votes: 329, id: 1079450 },
    countries: [ 'Spain' ],
    type: 'movie',
    tomatoes: {
    website: 'http://www.pereportabella.com/eng/fla/die/home_eng.html',
    viewer: { rating: 3.5, numReviews: 391, meter: 64 },
    critic: { rating: 6.6, numReviews: 16, meter: 81 },
    lastUpdated: ISODate('2015-08-11T19:15:49.000Z'),
    rotten: 3,
    production: 'Film Forum',
    fresh: 13
    },
    num_mflix_comments: 0
    },
    {
    _id: ObjectId('573a13ccf29313caabd83260'),
    plot: 'A woman subject to mental, physical, and sexual abuse on a remote island seeks a way out.',
    genres: [ 'Crime', 'Drama', 'Horror' ],
    runtime: 115,
    cast: [ 'Yeong-hie Seo', 'Seong-won Ji', 'Min-ho Hwang', 'Min Je' ],
    num_mflix_comments: 0,
    poster: 'https://m.media-amazon.com/images/M/MV5BMjAyNDEwMDgzMl5BMl5BanBnXkFtZTcwNzMyMTYwNQ@@._V1_SY1000_SX677_AL_.jpg',
    title: 'Bedevilled',
    fullplot: "Hae-won is a beautiful single woman in her thirties who works at a bank in the Seoul city. She leads a busy life until she becomes a witness to an attempted murder case, and at the same time, things get complicated at work. When things get out of hand she is forced to take a vacation so she heads for 'Moodo', a small undeveloped island, where she had once visited to see her grandparents. And where she had befriended a girl named Bok-nam who stills writes to Hae-won asking her to visit despite the fact that Hae-won never bothered to reply. Upon arriving at the island, Hae-won is shocked to see everyone treating Bok-nam like a slave. As practically the only young woman on the island, she is a plaything for all the men and a free laborer for the women. Sick of all the inhumane treatment, Bok-nam had tried to escape the island several times in the past but had failed each time. She begs Hae-won to help her escape the place, but Hae-won remains indifferent not wanting to be involved in complicated situations. When Bok-nam realizes that her own daughter will follow her footsteps, she tries to escape the island with her daughter.",
    languages: [ 'Korean' ],
    released: ISODate('2010-09-02T00:00:00.000Z'),
    directors: [ 'Cheol-soo Jang' ],
    writers: [ 'Kwang-young Choi' ],
    awards: { wins: 10, nominations: 5, text: '10 wins & 5 nominations.' },
    lastupdated: '2015-09-01 01:18:02.960000000',
    year: 2010,
    imdb: { rating: 7.3, votes: 7983, id: 1646959 },
    countries: [ 'South Korea' ],
    type: 'movie'
    },
    {
    _id: ObjectId('573a13c7f29313caabd746fe'),
    plot: 'A Californian family inherits a castle in Romania. This is especially exciting to the son, who is obsessed with monsters. And he is not disappointed.',
    genres: [ 'Comedy', 'Family' ],
    runtime: 83,
    rated: 'TV-G',
    cast: [
    'Victoria Justice',
    'Chase Ellison',
    'Anna Galvin',
    'Matt Winston'
    ],
    num_mflix_comments: 0,
    poster: 'https://m.media-amazon.com/images/M/MV5BMjU1MmJlMTctY2FiMC00MmU1LWI5NmYtMDc5OWM0NjEzMmI2XkEyXkFqcGdeQXVyNDgyODgxNjE@._V1_SY1000_SX677_AL_.jpg',
    title: 'The Boy Who Cried Werewolf',
    fullplot: 'A Californian family inherits a castle in Romania. This is especially exciting to the son, who is obsessed with monsters. And he is not disappointed.',
    languages: [ 'English' ],
    released: ISODate('2010-10-22T00:00:00.000Z'),
    directors: [ 'Eric Bross' ],
    writers: [ 'Art Edler Brown', 'Douglas Sloan' ],
    awards: { wins: 1, nominations: 2, text: '1 win & 2 nominations.' },
    lastupdated: '2015-08-20 00:01:59.673000000',
    year: 2010,
    imdb: { rating: 6.3, votes: 1582, id: 1451423 },
    countries: [ 'USA', 'Canada' ],
    type: 'movie',
    tomatoes: {
    viewer: { rating: 3.7, numReviews: 762, meter: 66 },
    lastUpdated: ISODate('2015-09-12T17:30:20.000Z')
    }
    },
    {
    _id: ObjectId('573a13b4f29313caabd3f473'),
    genres: [ 'Documentary' ],
    runtime: 85,
    title: 'Zero Degrees of Separation',
    countries: [ 'Canada' ],
    lastupdated: '2015-08-09 00:30:38.977000000',
    languages: [ 'Arabic', 'English', 'Hebrew' ],
    released: ISODate('2005-06-22T00:00:00.000Z'),
    directors: [ 'Elle Flanders' ],
    writers: [ 'Elle Flanders' ],
    awards: { wins: 1, nominations: 0, text: '1 win.' },
    year: 2005,
    imdb: { rating: 6.6, votes: 90, id: 454990 },
    type: 'movie',
    tomatoes: {
    viewer: { rating: 3.5, numReviews: 5, meter: 100 },
    fresh: 1,
    critic: { numReviews: 2 },
    rotten: 1,
    lastUpdated: ISODate('2015-01-04T23:25:58.000Z')
    },
    num_mflix_comments: 0
    },
    {
    _id: ObjectId('573a13bff29313caabd5f070'),
    plot: 'This hilarious genre-bending comedy follows Gary Brewer, along with girlfriend Holly Brewer (no relation), and best friend Trevor Morehouse as Gary quests to reign supreme at the 2006 Rock, Paper, Scissors World Championships.',
    genres: [ 'Comedy' ],
    runtime: 85,
    cast: [ 'Tim Doiron', 'April Mullen', 'Ryan Tilley', 'Peter Pasyk' ],
    num_mflix_comments: 0,
    poster: 'https://m.media-amazon.com/images/M/MV5BMTI5MzIwMjA2Ml5BMl5BanBnXkFtZTcwOTcyOTA4MQ@@._V1_SY1000_SX677_AL_.jpg',
    title: 'Rock, Paper, Scissors: The Way of the Tosser',
    fullplot: 'This hilarious genre-bending comedy follows Gary Brewer, along with girlfriend Holly Brewer (no relation), and best friend Trevor Morehouse as Gary quests to reign supreme at the 2006 Rock, Paper, Scissors World Championships.',
    languages: [ 'English' ],
    released: ISODate('2007-07-06T00:00:00.000Z'),
    directors: [ 'Tim Doiron', 'April Mullen' ],
    writers: [ 'Tim Doiron (creator)', 'April Mullen (creator)', 'Tim Doiron' ],
    awards: { wins: 2, nominations: 0, text: '2 wins.' },
    lastupdated: '2015-08-12 00:01:33.813000000',
    year: 2007,
    imdb: { rating: 6.2, votes: 316, id: 1121964 },
    countries: [ 'Canada' ],
    type: 'movie'
    }
    ]
  2. Create a search index on the collection with the sample data using the index definition you want to use for your full collection:

    db.sample_data.createSearchIndex(
    "sample-index",
    { mappings: { dynamic: true } }
    )
    sample-index
  3. Scale the size of the sample data by the total size of the collection. For example, if the size of the sample-index index is 44.88, according to the Atlas UI Index Overview page, then you can use the following commands to calculate your total index size:

    let sampleSize = db.sample_data.totalSize()
    let totalSize = db.movies.totalSize()
    let totalIndexSize = ( 44.88 / sampleSize ) * totalSize; totalIndexSize
    45864.28

To learn how to define an Atlas Search index to meet your Atlas Search query needs, see Define Your Query.

To learn how to create an Atlas Search index, see Create an Atlas Search index.

To learn more about the Atlas Search index configurations described in this tutorial, see the following reference pages:

For hands-on experience creating Atlas Search indexes for the sample datasets and running Atlas Search queries against the indexed data, try the Atlas Search Quick Start.

Follow along with this video tutorial walk-through that demonstrates how to create Atlas Search indexes of various complexity.

Duration: 15 Minutes

Back

Queries & Indexes