“文档” 菜单
文档首页
/
MongoDB Manual
/ / /

在数组字段上创建索引

在此页面上

  • 关于此任务
  • 步骤
  • 结果
  • 了解详情

您可以在包含数组值的字段上创建索引,以优化对该字段的查询性能。当您在含有数组值的字段上创建索引时,MongoDB 会将该索引存储为多键索引。

要创建索引,请使用 db.collection.createIndex()方法。您的操作应类似于以下原型:

db.<collection>.createIndex( { <field>: <sortOrder> } )

本页的示例使用包含以下文档的 students 集合:

db.students.insertMany( [
{
"name": "Andre Robinson",
"test_scores": [ 88, 97 ]
},
{
"name": "Wei Zhang",
"test_scores": [ 62, 73 ]
},
{
"name": "Jacob Meyer",
"test_scores": [ 92, 89 ]
}
] )

您定期运行一个查询,该查询会返回至少一个 test_score 大于 90 的学生。您可对 test_scores 字段创建索引,从而为此查询提高性能。

以下操作将在 students 集合的 test_scores 字段上创建升序多键索引:

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

由于 test_scores 包含数组值,因此 MongoDB 会将此索引存储为多键索引。

该索引包含 test_scores 字段中显示的每个单独值的键。索引为升序,即按此顺序存储键值:[ 62, 73, 88, 89, 92, 97 ]

该索引支持选择 test_scores 字段的查询。例如,以下查询返回 test_scores 数组中至少有一个元素大于 90 的文档:

db.students.find(
{
test_scores: { $elemMatch: { $gt: 90 } }
}
)

输出:

[
{
_id: ObjectId("632240a20646eaee87a56a80"),
name: 'Andre Robinson',
test_scores: [ 88, 97 ]
},
{
_id: ObjectId("632240a20646eaee87a56a82"),
name: 'Jacob Meyer',
test_scores: [ 92, 89 ]
}
]
← 多键索引