目录
一、MongoDB官网地址
- 一、MongoDB官网地址
- 二、多键索引(Multikey Index)
- 2.1、多键索引(Multikey Index)的概述
- 2.1、多键索引(Multikey Index)的官网图解
- 三、数据准备
- 四、创建多键索引的示例
- 五、创建复合多键索引
- 5.1、创建升序复合多键索引的示例
- 5.2、在包含嵌套对象的数组字段上创建多键索引的示例
- 5.2.1、数据准备
- 5.2.2、在包含嵌套对象的数组字段上创建多键索引
- 六、注意事项
- MongoDB官网地址:https://www.mongodb.com/docs/manual/core/index-single/
- 在数组的属性上建立索引。针对这个数组的任意值的查询都会定位到这个文档,既多个索引入口或者键值引用同一个文档。
-
准备数据集,执行脚本
db.inventory.insertMany([ { _id: 5, type: "food", item: "aaa", ratings: [ 5, 8, 9 ] }, { _id: 6, type: "food", item: "bbb", ratings: [ 5, 9 ] }, { _id: 7, type: "food", item: "ccc", ratings: [ 9, 5, 8 ] }, { _id: 8, type: "food", item: "ddd", ratings: [ 9, 5 ] }, { _id: 9, type: "food", item: "eee", ratings: [ 5, 9, 5 ] } ])
-
查看初始化的数据
> db.inventory.find()
-
在集合inventory中的数组类型字段ratings上创建升序多键索引
> db.inventory.createIndex( { ratings: 1 } )
-
查看创建的多键索引
> db.inventory.getIndexes()
- 多键索引很容易与复合索引产生混淆,复合索引是多个字段的组合,而多键索引则仅仅是在一个字段上出现了多键(multi key)。而实质上,多键索引也可以出现在复合字段上。
-
在集合inventory中的数组类型字段ratings上和item字段上创建升序复合多键索引
> db.inventory.createIndex( { item:1,ratings: 1} )
-
查看创建的复合多键索引
> db.inventory.getIndexes()
-
准备数据集,执行脚本
db.inventory.insertMany([ { _id: 1, item: "abc", stock: [ { size: "S", color: "red", quantity: 25 }, { size: "S", color: "blue", quantity: 10 }, { size: "M", color: "blue", quantity: 50 } ] }, { _id: 2, item: "def", stock: [ { size: "S", color: "blue", quantity: 20 }, { size: "M", color: "blue", quantity: 5 }, { size: "M", color: "black", quantity: 10 }, { size: "L", color: "red", quantity: 2 } ] } ])
-
查看初始化的数据
> db.inventory.find()
-
嵌套对象的数组字段上创建多键索引
> db.inventory.createIndex( { "stock.size": 1, "stock.quantity": 1 } )
-
查看在嵌套对象的数组字段上创建多键索引
> db.inventory.getIndexes()
- 注意: MongoDB并不支持一个复合索引中同时出现多个数组字段。