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

在单个字段上创建索引

您可以在单个字段上创建索引,提高对该字段的查询性能。

要创建单字段索引,请使用 db.collection.createIndex() 方法:

db.<collection>.createIndex( { <field>: <sort-order> } )

创建一个 students 集合,其中包含以下文档:

db.students.insertMany( [ { "name": "Alice", "gpa": 3.6, "location": { city: "Sacramento", state: "California" } }, { "name": "Bob", "gpa": 3.2, "location": { city: "Albany", state: "New York" } }] )

以下示例展示了如何:

考虑一位学校管理员,他经常根据学生的 GPA 查找学生。您可以在 gpa 字段上创建索引,以提高这些查询的性能:

db.students.createIndex( { gpa: 1 } )

该索引支持选择字段gpa的查询,如下所示:

db.students.find( { gpa: 3.6 } ) db.students.find( { gpa: { $lt: 3.4 } } )

您可以对嵌入式文档中的字段创建索引。 嵌入式字段上的索引可以完成使用点表示法的查询。

location 字段是嵌入式文档,其中包含嵌入式字段 city 和 state。在 location.state 字段上创建索引:

db.students.createIndex( { "location.state": 1 } )

该索引支持对字段location.state进行查询,如下所示:

db.students.find( { "location.state": "California" } ) db.students.find( { "location.city": "Albany", "location.state": "New York" } )