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.
Index Limitations
You cannot create more than:
3 indexes on
M0
clusters.5 indexes on
M2
clusters.10 indexes on
M5
clusters.
We recommend that you create no more than 2,500 search indexes on a single
M10+
cluster.To create an Atlas Search index from Compass, you must have an
M10+
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" } ])
[ { _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' } ]
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 it's not already displayed, click Clusters 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. |
<IndexName> | 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, "<indexName>"); 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.