MongoDB——索引类型之多键索引(Multikey Index)

一、MongoDB官网地址

二、多键索引(Multikey Index)

2.1、多键索引(Multikey Index)的概述

  • 在数组的属性上建立索引。针对这个数组的任意值的查询都会定位到这个文档,既多个索引入口或者键值引用同一个文档。

2.1、多键索引(Multikey Index)的官网图解

在这里插入图片描述

三、数据准备

  • 准备数据集,执行脚本

    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)。而实质上,多键索引也可以出现在复合字段上。

5.1、创建升序复合多键索引的示例

  • 在集合inventory中的数组类型字段ratings上和item字段上创建升序复合多键索引

    > db.inventory.createIndex( { item:1,ratings: 1} )
    

    在这里插入图片描述

  • 查看创建的复合多键索引

    > db.inventory.getIndexes()
    

    在这里插入图片描述

5.2、在包含嵌套对象的数组字段上创建多键索引的示例

5.2.1、数据准备
  • 准备数据集,执行脚本

    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()
    

    在这里插入图片描述

5.2.2、在包含嵌套对象的数组字段上创建多键索引
  • 嵌套对象的数组字段上创建多键索引

    > db.inventory.createIndex( { "stock.size": 1, "stock.quantity": 1 } )
    

    在这里插入图片描述

  • 查看在嵌套对象的数组字段上创建多键索引

    > db.inventory.getIndexes()
    

    在这里插入图片描述

六、注意事项

  • 注意 MongoDB并不支持一个复合索引中同时出现多个数组字段。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小志的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值