文档菜单
文档首页
/
MongoDB 手册
/ /

指定索引名称

本页内容

  • 关于此任务
  • 默认索引名称
  • 过程
  • 结果
  • 了解更多

当您创建索引时,您可以给索引一个自定义名称。给索引命名有助于区分集合中的不同索引。例如,如果您的索引有独特的名称,您可以在查询计划的解释结果中更容易识别查询所使用的索引。

要指定索引名称,在创建索引时包括name 选项

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

在指定索引名称之前,请考虑以下事项

  • 索引名称必须是唯一的。使用已存在的索引名称创建索引会返回错误。

  • 您不能重命名现有索引。相反,您必须删除并使用新名称重新创建索引。

如果您在创建索引时未指定名称,系统会通过将每个索引键字段和值使用下划线连接起来生成名称。例如

索引
默认名称
{ 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

一个 博客 集合包含有关博客文章和用户交互的数据。

contentusers.commentsusers.profiles 字段上创建文本索引。将索引的 name 设置为 InteractionsTextIndex

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

索引创建完成后,您可以使用 db.collection.getIndexes() 方法获取索引名称

db.blog.getIndexes()

输出

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

返回

创建