Create an Atlas Search Index
On this page
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
Prerequisites
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.
Required Access
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. | ✓ | ✓ | ||
Project Data Access Admin or higher role | To create and manage Atlas Search analyzers and indexes, and
assign the role to your API Key. | ✓ | ✓ | ✓ | ✓ |
Project Owner role | ✓ | ✓ | |||
Organization Owner role | 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.
Free and Shared Cluster Limitations
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.
Estimate the Size of Your Index
You can estimate the size of your index by creating an index on a subset of your collection:
Take a sample of your data and create a new collection with the sample data.
Create a search index on the collection with the sample data.
Note
The index definition for the sample data must be the same as the index definition you want to create on the full collection.
Scale the size of the sample data index based on the total size of your data.
estimated-index-size = ( subset-data-index-size / subset-data-size ) x total-collection-data-size
Example
This example uses the sample_mflix.movies
namespace. We first run
$sample
to randomly select 10 documents from the
movies
collection and create a new collection named
sample_data
that contains the $sample
output documents:
db.movies.aggregate([ { $sample: { size: 10 } }, { $out: "sample_data" } ])
Next, for the $sample
output data that we added to the
sample_data
collection by using $out
, we create an
index on just the title
field:
{ "mappings": { "dynamic": false, "fields": { "title": { "type": "string" } } } }
The size of the index on the title
field in the sample_data
collection with 10 documents is 4.34 KB. The size of the
sample_data
collection is 14.19 KB. The total size of the
movies
collection is 32.54 MB, which is 32540 KB. We use the
following calculations to estimate the index size for the entire
movies
collection:
4.34 KB / 14.19 KB = 0.30584918957012 KB (per document) 0.30584918957012 KB x 32540 KB = 9952.3326286117048 KB 9265.466 KB x 0.001 MB = 9.952332628611705 MB
The estimated size index size for the title
field in the
movies
collection is 9.95 MB. However, the index size for the
movies
collection might vary based on the length of the titles in
the other non-sampled documents.
Create an Atlas Search Index
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
Atlas Search indexes must apply to a full collection, rather than to only a portion of a collection.
➤ Use the Select your language drop-down menu to set the language of the example in this section.
To create an Atlas Search index:
Send a POST
request.
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.
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.
Create an Atlas Search Index for a Cloud 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.
Create an Atlas Search Index for a Local Deployment
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.
Example
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.
For $search
queries, you create an index of the
default search
type.
Procedure
To create an Atlas Search index from the Atlas UI:
In Atlas, go to the Clusters page for your project.
If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it's not already displayed, select your desired project from the Projects menu in the navigation bar.
If the Clusters page is not already displayed, click Database in the sidebar.
The Clusters page displays.
Go to the Atlas Search page for your cluster.
You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.
In the sidebar, click Atlas Search under the Services heading.
From the Select data source dropdown, select your cluster and click Go to Atlas Search.
The Atlas Search page displays.
Click the Browse Collections button for your cluster.
Expand the database and select the collection.
Click the Search Indexes tab for the collection.
The Atlas Search page displays.
Click the cluster's name.
Click the Atlas Search tab.
The Atlas Search page displays.
Enter the Index Name, and set the Database and Collection.
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.
If you name your index
default
, you don't need to specify anindex
parameter in the $search pipeline stage. If you give a custom name to your index, you must specify this name in theindex
parameter.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.
If you use the Visual Editor, click Next.
Review the default Atlas Search index configuration settings in the Index Configurations section.
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 | 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:
Corresponds to the | Optional |
Dynamic Mapping | Specify dynamic or static mapping of fields. To disable dynamic
mapping, set Corresponds to the | Required |
Field Name | Description | Necessity |
---|---|---|
analyzer | 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: | Optional |
mappings.dynamic | Specify dynamic or static mapping of fields. To disable dynamic
mapping, set | 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.
Refine your Atlas Search index to configure additional settings.
If you are using the Visual Editor:
Click Refine Your Index to make changes to any of the following settings.
Field NameDescriptionNecessityField MappingsRequired if Dynamic Mapping in the Index Configurations section is disabled.
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:
Click Add Field to open the Add Field Mapping window.
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.
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.
You can define fields in the Atlas Search index definition in any order.
Corresponds to the
mappings.fields
JSON setting.ConditionalStored Source FieldsSpecify 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:Select the field to store on Atlas Search from the dropdown in the Field Name column.
Click Add to add the field to the list of fields to store.
Click Add Field and repeat steps a and b for each field to add to the list.
(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.
Select the field to exclude from the dropdown in the Field Name column.
Click Add to add the field to the list of fields to exclude.
Click Add Field, and repeat steps a and b for each field to exclude from the list.
(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.OptionalSynonyms MappingsSpecify 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.
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:
lucene.kuromoji
lucene.cjk
Custom analyzer token filters:
daitchMokotoffSoundex Token Filter
nGram Token Filter
edgeGram Token Filter
shingle Token Filter
Corresponds to the
synonyms
JSON setting.Optional.Click Save Changes.
If you are using the Atlas Search JSON Editor, do the following:
Add any of the following settings to your index:
Field NameDescriptionNecessitymappings.fields
Required if
mappings.dynamic
isfalse
.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.
You can define fields in the Atlas Search index definition in any order.
ConditionalstoredSource
Specify fields in the documents to store on Atlas Search. Value can be one of the following:
true
, to store all fieldsfalse
, to not store any fieldsObject that specifies the fields to
include
orexclude
from storage
If omitted, defaults to
false
.storedSource
is only available on Atlas clusters running one of the following versions:MongoDB 5.0.6+
MongoDB 6.0+
MongoDB 7.0+
You can store fields of all supported Data Types on Atlas Search. To learn more about the syntax and fields, see Define Stored Source Fields in Your Atlas Search Index.
Optionalsynonyms
Specify synonym mappings to use in your index. To learn more, see Define Synonym Mappings in Your Atlas Search Index.
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"
).OptionalTo learn more about these index definition settings, see Review Atlas Search Index Syntax.
Click Next.
Optional. If you use the Visual Editor, you can save or delete your index definition draft.
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.
Click Cancel.
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.
Check the status.
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.
Prefer to Learn by Watching?
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
:
Connect using mongosh
.
To learn more, see Connect via mongosh
.
Create an Atlas Search index.
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
Connect to your Atlas cluster in MongoDB Compass.
Open Compass and connect to your Atlas cluster. For detailed instructions on connecting, see Connect via Compass.
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.
Copy the following code example into the file.
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.
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:
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; }
Specify the following values and save the file.
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 Review Atlas Search Index Syntax.
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.
Copy the following code example into the file.
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.
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:
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; }
Specify the following values and save the file.
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 Review Atlas Search Index Syntax.
Create One Index
To use the .NET/C# Driver to create an Atlas Search index:
Construct a
BsonDocument
that defines the index.Pass the
BsonDocument
to theCreateOne()
orCreateOneAsync()
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.
Create a new directory and initialize your project.
Run the following command to create a new directory called
csharp-create-index
.mkdir csharp-create-index Run the following command to change to the new directory.
cd csharp-create-index Run the following command to initialize your project.
dotnet new console
Replace the contents of the Program.cs
file with a BsonDocument
that defines the index.
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
.
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);
Create Multiple Indexes
To create multiple Atlas Search indexes at once:
Construct an instance of
IEnumerable<CreateSearchIndexModel>
that contains the search index definitions.Pass the collection to the
CreateMany()
orCreateManyAsync()
method.
The following example shows how to use the CreateMany()
method to
create multiple indexes:
Create a new directory and initialize your project.
Run the following command to create a new directory called
csharp-create-index
.mkdir csharp-create-index-mult Run the following command to change to the new directory.
cd csharp-create-index-mult Run the following command to initialize your project.
dotnet new console
Replace the contents of the Program.cs
file with a BsonDocument
that defines the index.
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);
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.
Copy the following code example into the file.
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)); } } }
Specify the following values and save the file.
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
.
The fields to define your search index. To learn more, see Review Atlas Search Index Syntax.
Create One Index
To create an Atlas Search index through the Node Driver:
Define the search index from your application.
Run the
createSearchIndex
orcreateSearchIndexes
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.
Define the search index.
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 . |
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);
Create Multiple Indexes
To create multiple Atlas Search indexes at once:
In your application, define an array of search indexes.
Pass the array into the
createSearchIndexes
command.
The following example shows how to use the createSearchIndexes
command to create multiple indexes:
Define the search index.
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);
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.
Example
Copy the following code example into the file.
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)
Specify the following values and save the file.
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 Review Atlas Search Index Syntax.
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 Review 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.