Docs HomeDevelop ApplicationsMongoDB Manual

Specify an Index Name指定索引名称

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:要指定索引名称,请在创建索引时包含name选项:

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

About this Task任务介绍

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.不能重命名现有索引。相反,您必须删除索引并使用新名称重新创建索引。

Default Index Names默认索引名称

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

Procedure过程

A blog collection contains data about blog posts and user interactions.blog集合包含有关博客文章和用户交互的数据。

Create a text index on the content, users.comments, and users.profiles fields. contentusers.commentsusers.profiles字段上创建文本索引。Set the index name to InteractionsTextIndex:将索引name设置为InteractionsTextIndex

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

Results结果

After you create the index, you can use the db.collection.getIndexes() method to get the index name:创建索引后,可以使用db.collection.getIndexes()方法获取索引名称:

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
}
]

Learn More了解更多信息