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

x33g5p2x  于2022-05-05 转载在 其他  
字(1.8k)|赞(0)|评价(0)|浏览(386)

一、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并不支持一个复合索引中同时出现多个数组字段。

相关文章