目录
一、MongoDB官网地址
- 一、MongoDB官网地址
- 二、稀疏索引(Sparse Indexes)的概述
- 三、稀疏索引(Sparse Indexes)的特性
- 四、稀疏索引(Sparse Indexes)的语法
- 五、稀疏索引(Sparse Indexes)的示例1
- 5.1、数据准备
- 5.2、创建稀疏索引
- 5.3、测试1:查看是否使用稀疏索引
- 5.4、测试2:通过索引字段排序,查看是否使用稀疏索引
- 5.5、测试3:测试2中如果要使用稀疏索引,需要使用hint()显式指定索引
- 六、稀疏索引(Sparse Indexes)的示例2
- 6.1、先删除创建的稀疏索引
- 6.2、创建具有唯一约束的稀疏索引
- 6.2、测试1:插入具有唯一的分数字段值或不包含分数字段的文档
- 6.3、测试2:插入已存在评分为82和90的数据
- MongoDB官网地址:https://www.mongodb.com/docs/manual/core/index-single/
-
索引的稀疏属性确保索引只包含具有索引字段的文档的条目,索引将跳过没有索引字段的文档。
-
如果稀疏索引会导致查询和排序操作的结果集不完整,MongoDB将不会使用该索引,除非hint()明确指定索引。
-
同时具有稀疏性和唯一性的索引可以防止集合中存在字段值重复的文档,但允许不包含此索引字段的文档插入。
-
只对存在字段的文档进行索引(包括字段值为null的文档)
-
不索引不包含xmpp_id字段的文档
db.collection.createIndex( { "xmpp_id": 1 }, { sparse: true } )
-
语法
db.collection.createIndex( { fileName: 1 } , { sparse: true } )
-
初始化数据
db.scores.insertMany([ {"userid" : "newbie"}, {"userid" : "abby", "score" : 82}, {"userid" : "nina", "score" : 90} ])
-
查看初始化的数据
db.getCollection('scores').find({})
-
再scores集合中的score字段创建稀疏索引
db.scores.createIndex( { score: 1 } , { sparse: true } )
-
查询分数小于90的数据
db.scores.find( { score: { $lt: 90 } } )
-
通过执行计划查看是否使用索引
db.scores.find( { score: { $lt: 90 } } ).explain()
-
通过分数倒叙排序,然后查询数据
db.scores.find().sort( { score: -1 } )
-
通过执行计划查看是否使用索引
db.scores.find().sort( { score: -1 } ).explain()
-
要使用稀疏索引,使用hint()显式指定索引,由下图结果显示,虽然使用了索引,但是丢失一条数据。
db.scores.find().sort( { score: -1 } ).hint( { score: 1 } )
-
通过执行计划查看是否使用索引
db.scores.find().sort( { score: -1 } ).hint( { score: 1 } ).explain()
-
查询索引名称
db.scores.getIndexes()
-
根据索引名称删除索引
db.scores.dropIndex("score_1")
- 再scores集合中的score字段创建唯一约束的稀疏索引
db.scores.createIndex({score:1},{sparse:true,unique:true})
-
由下图结果可知,唯一约束的稀疏索引将允许插入具有唯一的分数字段值或不包含分数字段的文档。
db.scores.insertMany([ {"userid": "AAAAAAA","score":43}, {"userid": "BBBBBBB","score":34}, {"userid": "CCCCCCC"}, {"userid": "CCCCCCC"} ])
-
由下图结果可知,唯一约束的稀疏索引不允许添加下列文件,因为已经存在评分为82和90的文件
db.scores.insertMany( [ {"userid":"AAAAAAA","score":82}, {"userid":"BBBBBBB","score":90} ])