您可以在单个字段上创建索引,提高对该字段的查询性能。
要创建单字段索引,请使用 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" } )