Docs Home → Develop Applications → MongoDB Manual
Specify an Index Name指定索引名称
On this page本页内容
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:例如:
{ 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. content
、users.comments
和users.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了解更多信息
To learn how to create an index, see Create an Index.要了解如何创建索引,请参阅创建索引。For more information about index properties, see Index Properties.有关索引属性的详细信息,请参阅索引属性。