为数组中的嵌入字段创建索引
您可以在数组中的嵌入式文档字段上创建索引。这些索引可提高对数组中的特定嵌入字段进行查询的性能。当您在数组中的字段上创建索引时,MongoDB 会将该索引存储为多键索引。
要创建索引,请使用 db.collection.createIndex()
方法。 您的操作应类似于以下原型:
db.<collection>.createIndex( { <field>: <sortOrder> } )
关于此任务
本页上的示例使用包含以下文档的 inventory
集合:
db.inventory.insertMany( [ { "item": "t-shirt", "stock": [ { "size": "small", "quantity": 8 }, { "size": "large", "quantity": 10 }, ] }, { "item": "sweater", "stock": [ { "size": "small", "quantity": 4 }, { "size": "large", "quantity": 7 }, ] }, { "item": "vest", "stock": [ { "size": "small", "quantity": 6 }, { "size": "large", "quantity": 1 } ] } ] )
每当库存少于 5 件商品时,您都需要订购更多库存。要查找要重新排序的项目,可以查询 stock
数组中某个元素的 quantity
小于 5
的文档。若要提高此查询的性能,可以在 stock.quantity
字段上创建索引。
步骤
以下操作将在 inventory
集合的 stock.quantity
字段上创建升序多键索引:
db.inventory.createIndex( { "stock.quantity": 1 } )
由于 stock
包含数组值,因此 MongoDB 会将此索引存储为多键索引。
结果
该索引包含 stock.quantity
字段中显示的每个单独值的键。索引为升序,即按此顺序存储键值:[ 1, 4, 6, 7, 8, 10 ]
。
该索引支持选择 stock.quantity
字段的查询。例如,以下查询会返回 stock
数组中至少有一个元素的quantity
少于 5
的文档:
db.inventory.find( { "stock.quantity": { $lt: 5 } } )
输出:
[ { _id: ObjectId("63449793b1fac2ee2e957ef3"), item: 'vest', stock: [ { size: 'small', quantity: 6 }, { size: 'large', quantity: 1 } ] }, { _id: ObjectId("63449793b1fac2ee2e957ef2"), item: 'sweater', stock: [ { size: 'small', quantity: 4 }, { size: 'large', quantity: 7 } ] } ]
对结果进行排序
该索引还支持对 stock.quantity
字段进行排序操作,例如以下查询:
db.inventory.find().sort( { "stock.quantity": -1 } )
输出:
[ { _id: ObjectId("63449793b1fac2ee2e957ef1"), item: 't-shirt', stock: [ { size: 'small', quantity: 8 }, { size: 'large', quantity: 10 } ] }, { _id: ObjectId("63449793b1fac2ee2e957ef2"), item: 'sweater', stock: [ { size: 'small', quantity: 4 }, { size: 'large', quantity: 7 } ] }, { _id: ObjectId("63449793b1fac2ee2e957ef3"), item: 'vest', stock: [ { size: 'small', quantity: 6 }, { size: 'large', quantity: 1 } ] } ]
当对对象数组进行降序排序时,MongoDB 首先根据拥有最大值元素的字段进行排序。
注意
索引排序顺序
使用降序单字段索引可能会对索引性能产生负面影响。 为获得最佳性能,请仅使用升序单字段索引。