您当前的位置: 首页 >  mongodb

小志的博客

暂无认证

  • 0浏览

    0关注

    1217博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

小志的博客 发布时间:2022-05-02 22:49:16 ,浏览量:0

目录
    • 一、MongoDB官网地址
    • 二、多键索引(Multikey Index)
      • 2.1、多键索引(Multikey Index)的概述
      • 2.1、多键索引(Multikey Index)的官网图解
    • 三、数据准备
    • 四、创建多键索引的示例
    • 五、创建复合多键索引
      • 5.1、创建升序复合多键索引的示例
      • 5.2、在包含嵌套对象的数组字段上创建多键索引的示例
        • 5.2.1、数据准备
        • 5.2.2、在包含嵌套对象的数组字段上创建多键索引
    • 六、注意事项

一、MongoDB官网地址
  • MongoDB官网地址:https://www.mongodb.com/docs/manual/core/index-single/
二、多键索引(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并不支持一个复合索引中同时出现多个数组字段。
关注
打赏
1661269038
查看更多评论
立即登录/注册

微信扫码登录

0.0458s