Docs Menu
Docs Home
/
MongoDB Atlas
/ /

Create an Atlas Search Index

On this page

  • Prerequisites
  • Required Access
  • Free and Shared Tier Cluster Limitations
  • Create an Atlas Search Index
  • Index Status

An Atlas Search index is a data structure that categorizes data in 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.

You can create an Atlas Search index for all collections except time series collections on your Atlas cluster through the Atlas UI, API, Atlas CLI, and Terraform.

Important

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

To create an Atlas Search index, you must have an Atlas cluster with:

  • MongoDB version 4.2 or higher on any cluster tier.

  • Collection for which to create the Atlas Search index.

The following table shows the modes of access each role supports.

Role
Action
Atlas UI
Atlas API
Atlas Search API
Atlas CLI
Project Data Access Read Only or higher role
To view Atlas Search analyzers and indexes.
✓
✓
To create and manage Atlas Search analyzers and indexes, and assign the role to your API Key.
✓
✓
✓
✓
✓
✓
To create access list entries for your API Key and send the request from a client that appears in the access list for your API Key.
✓
✓
To create, view, edit, and delete Atlas Search indexes using the Atlas UI or API.
✓
✓
✓

You must have at least the readWriteAnyDatabase role or readWrite access to the database where you want to create the indexes. To learn more, see Built-in Roles or Specific Privileges.

  • You cannot create more than:

    • 3 indexes on M0 clusters.

    • 5 indexes on M2 clusters.

    • 10 indexes on M5 clusters.

    There are no limits to the number of indexes you can create on M10+ clusters.

  • To create an Atlas Search index from Compass, you must have an M10 or higher Atlas cluster running MongoDB 7.0 or higher.

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

Note

You can't use the mongosh command or driver helper methods to create Atlas Search indexes on M0, M2, or M5 Atlas clusters. To create and manage Atlas Search indexes using mongosh or the driver, upgrade to a dedicated cluster tier.


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


To create an Atlas Search index:

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": "string",
"database": "string",
"name": "string",
"type": "search",
"definition":
{
"analyzer": "lucene.<analyzer>",
"analyzers": [
{
"charFilters": [ ... ],
"name": "string",
"tokenFilters": [ ... ],
"tokenizer": { ... }
}
],
"mappings": {
"dynamic": true | false,
"fields": {
"property1": {},
...
}
},
"searchAnalyzer": "lucene.<analyzer>",
"storedSource": {
"include | exclude": [...]
},
"synonyms": [
{
"analyzer": "lucene.<analyzer>",
"name": "string",
"source": {
"collection": "string"
}
}
]
}
}'

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.

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.

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.

Tip

See: Related Links

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.

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.

For $search queries, you create an index of the default search type.

To create an Atlas Search index from the Atlas UI:

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

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

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

2

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

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

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

  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.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

3
4
Screenshot of Create an Atlas Search Index modal window
click to enlarge
  • For a guided experience, select the Atlas Search Visual Editor.

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

5
  1. In the Index Name field, specify a name for the index.

    Index names must be unique within their namespace. The index name defaults to default. You can accept the default name or specify a different name.

    Note

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

  2. In the Database and Collection section, expand the database, and select the collection name.

    Tip

    If you navigated to this page from the Data Explorer, you can skip this step because Atlas preselects the database and collection that you selected in the Data Explorer.

  3. If you use the Visual Editor, click Next.

6

You can use either the default index definition or specify a custom index definition:

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

  • A custom index definition is a static mapping. You specify the fields to index, the analyzer, and the data type.

Field Name
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
Query 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. To disable dynamic mapping, set "dynamic": to Off. 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 Review Atlas Search Index Syntax.

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 Review Atlas Search Index Syntax.

Required

To learn more about these index definition settings, see Review Atlas Search Index Syntax.

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

7

If you are using the Visual Editor:

  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.

    Note

    Defining your own field mappings is recommended for advanced users only.

    Specify the fields to index. To add the fields, you must do the following:

    1. Click Add Field 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 Configuration - Field data type. To learn more about the supported data types and their options, see Data Types.

      • Enable Dynamic Mapping - Static or dynamic mapping to use for fields of document and embeddedDocument types. If you disable dynamic mapping, the data in the field isn't automatically indexed.

    3. Click Add to add the field.

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

      • Modify the settings for the field by clicking Edit.

      • Configure additional data types for the field by clicking Add Data Type.

      • Remove the field from the index by clicking Delete.

    Note

    Unlike compound indexes, the order of fields in the Atlas Search index definition is not important. Fields can be defined in any order.

    Corresponds to the mappings.fields JSON setting.

    Conditional
    Stored Source Fields

    Specify the fields to store on Atlas Search. You can choose one of the following:

    • None - (Default) If selected, Atlas Search doesn't store any field.

    • All - If selected, Atlas Search stores all the fields in the documents.

    • Specified - If selected, Atlas Search stores _id and the fields you specify. You can specify the fields by doing the following:

      1. Select the field to store on Atlas Search from the dropdown in the Field Name column.

      2. Click Add to add the field to the list of fields to store.

      3. Click Add Field and repeat steps a and b for each field to add to the list.

      4. (Optional) Click one of the following:

        • Edit to select a different field.

        • Delete to remove the field from the list of fields to store.

    • All Except Specified - If selected, Atlas Search excludes specific fields from storage on Atlas Search.

      1. Select the field to exclude from the dropdown in the Field Name column.

      2. Click Add to add the field to the list of fields to exclude.

      3. Click Add Field, and repeat steps a and b for each field to exclude from the list.

      4. (Optional) Click one of the following:

        • Edit to select a different field.

        • Delete to remove the field from the list of fields to exclude.

    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. To learn more, see Define Synonym Mappings in Your Atlas Search Index.

    To add synonym mappings, you must specify the following settings for each synonym:

    • Synonym mapping name - Label that identifies the synonym mapping to refer to at query time. You must specify a unique value. You can't specify an empty string value.

    • Synonym source collection - Label that identifies the MongoDB collection in the same database as the Atlas Search index. Documents in this collection use the format described in the Synonyms Source Collection Documents. You can also add an empty collection or load a sample collection.

    • Analyzer - Label that identifies the analyzer to use with this synonym mapping.

      Note

      You can use a synonym mapping to query only fields analyzed with the same analyzer. By default, Atlas Search uses the standard analyzer ("lucene.standard").

      You can specify any Atlas Search analyzer except the following:

    Corresponds to the synonyms JSON setting.

    Optional.
  2. Click Save Changes.

If you are using the Atlas Search JSON Editor, do the following:

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

    Field Name
    Description
    Necessity
    mappings.fields

    Required if mappings.dynamic is false.

    Note

    Defining your own field mappings is recommended for advanced users only.

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

    Note

    Unlike compound indexes, the order of fields in the Atlas Search index definition is not important. Fields can be defined in any order.

    Conditional
    storedSource

    Note

    storedSource is only available on Atlas clusters running one of the following versions:

    • MongoDB 5.0.6+

    • MongoDB 6.0+

    • MongoDB 7.0+

    Specify fields in the documents to store on Atlas Search. Value can be one of the following:

    • true, to store all fields

    • false, to not store any fields

    • Object that specifies the fields to include or exclude from storage

    If omitted, defaults to false. To learn more about the syntax and fields, see Define Stored Source Fields in Your Atlas Search Index.

    Note

    You can store fields of all supported Data Types on Atlas Search.

    Optional
    synonyms

    Specify synonym mappings to use in your index. To learn more, see Define Synonym Mappings in Your Atlas Search Index.

    Note

    You can use a synonym mapping to query only fields analyzed with the same analyzer. By default, Atlas Search uses the standard analyzer ("lucene.standard").

    Optional

    To learn more about these index definition settings, see Review Atlas Search Index Syntax.

  2. Click Next.

8

Note

If you use the Visual Editor and your index definition contains static mappings, you can save an index definition as a draft. You can't save the default index definition as a draft. You can save only a custom 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 about creating an index using an index draft, see Resume or Delete an Atlas Search Index Draft.

9

Atlas displays a modal window to let you know your index is building.

10
11

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.

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

Duration: 15 Minutes

To create an Atlas Search index through 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 Review Atlas Search Index Syntax.

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
1

Open Compass and connect to your Atlas cluster. For detailed instructions on connecting, 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 and then the search index definition.

    Index Name

    default

    Index Definition
    {
    mappings: { dynamic: true }
    }
  4. 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 that dynamically indexes the fields in your collection. 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 Review Atlas Search Index Syntax.

#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" : [ {
"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;
}
// 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;
}

You can also create multiple Atlas Search indexes at once. In the following example, define each search index that you want to create as a document inside the indexes array. Then, convert your command and search index information to BSON and call the mongoc_collection_command_simple() method to create 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 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.

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 Review Atlas Search Index Syntax.

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

The following sample application defines a search index to dynamically index the fields in your collection, then runs the CreateOne() method to create the index. To learn more, see Review Atlas Search Index Syntax.

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:

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.

You may also define the name of your index. If you omit the index name, Atlas Search names the index default.

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
{
{ "mappings", new BsonDocument
{
{ "dynamic", true }
}
}
};
var result = collection.SearchIndexes.CreateOne(index);
Console.WriteLine(result);
4

Use the following command to run the project:

dotnet run csharp-create-index.csproj
default

To create multiple Atlas Search indexes at once:

  1. Construct an instance of IEnumerable<CreateSearchIndexModel> that contains the search index definitions.

  2. Pass the collection to the CreateMany() or CreateManyAsync() method.

The following example shows how to use the CreateMany() method to create multiple indexes:

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

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

    cd csharp-create-index-mult
  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:

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.
<first-index-name>
Name of your first index.
<last-index-name>
Name of your last index.
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 indexes
var indexes = new List<CreateSearchIndexModel>
{
new CreateSearchIndexModel(
"<first-index-name>",
new BsonDocument
{
// search index definition fields
}
),
...
new CreateSearchIndexModel(
"<last-index-name>",
new BsonDocument
{
// search index definition fields
}
)
};
var result = collection.SearchIndexes.CreateMany(indexes);
4

Use the following command to run the project:

dotnet run csharp-create-index-mult.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. To learn more, refer to the Driver documentation.

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 Review Atlas Search Index Syntax.

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.

The following sample application named create-index.js defines a search index to dynamically index the fields in your collection, and then runs the createSearchIndex command to create the index. To learn more, see Review Atlas Search Index Syntax.

1
2

Replace the placeholder values in the following example:

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.
<index-name>
Name of your index. If you omit the index name, Atlas Search names the index default.
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 your Atlas Search index
const index = {
name: "<index-name>",
definition: {
/* search index definition fields */
"mappings": {
"dynamic": true
}
}
}
// run the helper method
const result = await collection.createSearchIndex(index);
console.log(result);
} finally {
await client.close();
}
}
run().catch(console.dir);
3

Use the following command:

node create-index.js
<index-name>

To create multiple Atlas Search indexes at once:

  1. In your application, define an array of search indexes.

  2. Pass the array into the createSearchIndexes command.

The following example shows how to use the createSearchIndexes command to create multiple indexes:

1
2

Replace the placeholder values in the following example:

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.
<first-index-name>
Name of your first index.
<last-index-name>
Name of your last index.
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-mult.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 Review Atlas Search Index Syntax.

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 Indexes tab in the right-side panel of the Atlas UI displays information about Atlas Search indexes for the selected namespace. The Status column shows the current state of the index on the primary node of the cluster. Click the View status details link below the status to view the state of the index on all the nodes of the cluster.

Screenshot of Atlas Search Index information panel
click to enlarge

When the Status column reads Active, the index is ready to use. In other states, queries against the index may return incomplete results.

Status
Description
Not Started
Atlas has not yet started building the index.
Initial Sync

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.

Active
Index is ready to use.
Recovering
Replication encountered an error. This state commonly occurs when the current replication point is no longer available on the mongod oplog. You can still query the existing index until it updates and its status changes to Active. 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.
Delete in Progress
Atlas is deleting the index from the cluster nodes.

While Atlas builds the index and after the build completes, the Documents column shows the percentage and number of documents indexed. The column also shows the total number of documents in the collection.

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.

Back

Create and Manage Indexes

Next

1: Process Data with Analyzers