MongoDB支持复合索引,即将多个键组合到一起创建索引。该方式称为复合索引,或者也叫组合索引,该方式能够满足多键值匹配查询使用索引的情形。其次复合索引在使用的时候,也可以通过前缀法来使用索引。MongoDB中的复合索引与关系型数据库基本上一致。在关系型数据库中复合索引使用的一些原则同样适用于MongoDB。
在前面的内容中,我们已经在emp集合上创建了一个复合索引,如下:
db.emp.createIndex({"deptno":1,"sal":-1})
下面使用不同的过滤条件查询文档,查看相应的执行计划:
(1)仅使用deptno作为过滤条件
db.emp.find({"deptno":10}).explain()
(2)使用deptno、sal作为过滤条件
db.emp.find({"deptno":10,"sal":3000}).explain()
(3)使用deptno、sal作为过滤条件,但把sal放在前面
db.emp.find({"sal":3000,"deptno":10}).explain()
(4)仅使用sal作为过滤条件
db.emp.find({"sal":3000}).explain()
复合索引创建时按升序或降序来指定其排列方式。对于单键索引,其顺序并不是特别重要,因为MongoDB可以在任一方向遍历索引。对于复合索引,按何种方式排序能够决定该索引在查询中能否被使用到。
db.emp.createIndex({"deptno":1,"sal":-1})
在前面的内容中,我们已经在deptno上按照升序、sal上按照降序建立了复合索引,下面测试不同的排序的下,是否执行了索引:
使用了索引的情况:
db.emp.find().sort({"deptno":1,"sal":-1}).explain()
db.emp.find().sort({"deptno":-1,"sal":1}).explain()
没有使用索引的情况:
db.emp.find().sort({"deptno":1,"sal":1}).explain()
db.emp.find().sort({"deptno":-1,"sal":-1}).explain()
交换两个列的位置,再进行测试。
索引前缀指的是复合索引的子集,假如存在如下索引:
db.emp.createIndex({"deptno":1,"sal":-1,"job":1})
那么就存在以下的索引前缀:
{"deptno":1}
{"deptno":1,"sal":-1}
在MongoDB中,下列查询过滤条件情形中,索引将会被使用到:
db.emp.find().sort({deptno:1,sal:-1,job:1}).explain()
db.emp.find().sort({deptno:1,sal:-1}).explain()
db.emp.find().sort({deptno:1}).explain()
下列查询过滤条件情形中,索引将不会被使用到:
db.emp.find().sort({deptno:1,job:1}).explain()
db.emp.find().sort({sal:-1,job:1}).explain()
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。