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. Set the index name to InteractionsTextIndex:content、users.comments和users.profiles文件字段上创建文本索引。将索引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.有关索引属性的详细信息,请参阅索引属性。