Docs Menu
Docs Home
/
MongoDB Atlas
/ /

Create an Atlas Search Index

On this page

  • Prerequisites
  • Required Access
  • Index Limitations
  • Estimate the Size of Your Index
  • Create an Atlas Search Index

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.

    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.

You can estimate the size of your index by creating an index on a subset of your collection:

  1. Take a sample of your data and create a new collection with the sample data.

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

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

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:

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's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.

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

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

    The Clusters page displays.

2

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

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

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

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3
4
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.

    If you name your index default, you don't need to specify an index parameter in the $search pipeline stage. If you give a custom name to your index, you must specify this name in 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.

    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.

    You can define fields in the Atlas Search index definition 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.

      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.

    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.

    Conditional
    storedSource

    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.

    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.

    Optional
    synonyms

    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").

    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.
<IndexName>
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, "<indexName>");
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 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.

Back

Create and Manage Indexes