Docs Menu
Docs Home
/
MongoDB Manual
/ /

Specify an Index Name

On this page

  • About this Task
  • Default Index Names
  • Procedure
  • Results
  • Learn More

When you create an index, you can give the index a custom name. Giving your index a name helps distinguish different indexes on your collection. For example, you can more easily identify the indexes used by a query in the query plan's explain results if your indexes have distinct names.

To specify the index name, include the name option when you create the index:

db.<collection>.createIndex(
{ <field>: <value> },
{ name: "<indexName>" }
)

Before you specify an index name, consider the following:

  • Index names must be unique. Creating an index with the name of an existing index returns an error.

  • You can't rename an existing index. Instead, you must drop and recreate the index with a new name.

If you don't specify a name during index creation, the system generates the name by concatenating each index key field and value with underscores. For example:

Index
Default Name

{ score : 1 }

score_1

{ content : "text", "description.tags": "text" }

content_text_description.tags_text

{ category : 1, locale : "2dsphere"}

category_1_locale_2dsphere

{ "fieldA" : 1, "fieldB" : "hashed", "fieldC" : -1 }

fieldA_1_fieldB_hashed_fieldC_-1

A blog collection contains data about blog posts and user interactions.

Create a text index on the content, users.comments, and users.profiles fields. Set the index name to InteractionsTextIndex:

db.blog.createIndex(
{
content: "text",
"users.comments": "text",
"users.profiles": "text"
},
{
name: "InteractionsTextIndex"
}
)

After you create the index, you can use the db.collection.getIndexes() method to get the index name:

db.blog.getIndexes()

Output:

[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{
v: 2,
key: { _fts: 'text', _ftsx: 1 },
name: 'InteractionsTextIndex',
weights: { content: 1, 'users.comments': 1, 'users.profiles': 1 },
default_language: 'english',
language_override: 'language',
textIndexVersion: 3
}
]

Back

Create