对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

指定索引名称

创建索引时,可以为索引指定自定义名称。为索引指定名称有助于区分集合中的不同索引。例如,如果您的索引具有不同名称,则可以更轻松地在查询计划的解释结果中识别查询使用的索引。

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

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

在指定索引名称之前,请考虑以下几点:

  • 索引名称必须是唯一的。使用已有索引的名称创建索引会报错。

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

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

Index
默认名称

{ 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

本页上的示例使用sample_mflix示例数据集中的数据。有关如何将此数据集加载到自管理MongoDB 部署中的详细信息,请参阅加载示例数据集。如果对示例数据库进行了任何修改,则可能需要删除并重新创建数据库才能运行本页上的示例。

Create a text index on the name and text fields. Set the index name to CommentsTextIndex:

db.comments.createIndex(
{
name: "text",
text: "text"
},
{
name: "CommentsTextIndex"
}
)
CommentsTextIndex

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

db.comments.getIndexes()
[
{
v: 2,
key: {
_id: 1
},
name: '_id_'
},
{
v: 2,
key: {
_fts: 'text',
_ftsx: 1
},
name: 'CommentsTextIndex',
weights: {
name: 1,
text: 1
},
default_language: 'english',
language_override: 'language',
textIndexVersion: 3
}
]