目录
一、MongoDB官网地址
- 一、MongoDB官网地址
- 二、通配符索引(Wildcard Indexes)的概述
- 三、通配符索引(Wildcard Indexes)的示例
- 3.1、准备商品数据,不同商品属性不一样
- 3.2、创建通配符索引
- 3.3、测试
- 四、通配符索引(Wildcard Indexes)的限制
- 4.1、通配符索引不支持以下索引类型或属性
- 4.2、通配符索引不能支持查询字段不存在的文档
- 4.3、通配符索引不能支持精确的文档或者数组相等匹配
- MongoDB官网地址:https://www.mongodb.com/docs/manual/core/index-single/
- MongoDB的文档模式是动态变化的,而通配符索引可以建立在一些不可预知的字段上,以此实现查询的加速。
- MongoDB 4.2 引入了通配符索引来支持对未知或任意字段的查询。
-
准备数据集,执行脚本
db.products.insert([ { "product_name" : "Spy Coat", "product_attributes" : { "material" : [ "Tweed", "Wool", "Leather" ], "size" : { "length" : 72, "units" : "inches" } } }, { "product_name" : "Spy Pen", "product_attributes" : { "colors" : [ "Blue", "Black" ], "secret_feature" : { "name" : "laser", "power" : "1000", "units" : "watts", } } }, { "product_name" : "Spy Book" } ])
-
查看初始化的数据
db.products.find()
-
创建通配符索引
db.products.createIndex( { "product_attributes.$**" : 1 } )
-
查看创建的通配符索引
> db.products.getIndexes()
-
通配符索引可以支持任意单字段查询 product_attributes或其嵌入字段
-
测试1
db.products.find( { "product_attributes.size.length" : { $gt : 60 } } )
-
测试2
> db.products.find( { "product_attributes.material" : "Leather" } ).pretty()
-
测试3
> db.products.find( { "product_attributes.secret_feature.name" : "laser" } ).pretty()
-
不支持以下索引类型或属性 (1)、 Compound (2)、TTL (3)、 Text (4)、 2d(Geospatial) (5)、2dsphere(Geospatial) (6)、 Hashed (7)、 Unique
-
示例:创建通配符索引的复合索引,提示不能创建此索引
db.products.createIndex( { "product_attributes.$**" : 1,"product_name":1 } )
通配符索引是稀疏的,不索引空字段。因此,通配符索引不能支持查询字段不存在的文档。
-
示例:
-
通配符索引不能支持以下查询,由下图可知,可以查询出数据。
db.products.find( {"product_attributes" : { $exists : false } } )
-
但是查看执行计划,发现是集合扫描(相当于全表扫描),没有走索引。
> db.products.find( {"product_attributes" : { $exists : false } } ).explain()
通配符索引为文档或数组的内容生成条目,而不是文档/数组本身。因此通配符索引不能支持精确的文档/数组相等匹配。通配符索引可以支持查询字段等于空文档{}的情况。
-
示例
-
通配符索引不能支持以下查询,由下图可知,可以查询出数据。
> db.products.find({ "product_attributes.colors" : [ "Blue", "Black" ] } )
-
但是查看执行计划,发现是集合扫描(相当于全表扫描),没有走索引。
> db.products.find({ "product_attributes.colors" : [ "Blue", "Black" ] } ).explain()