go mongodb排序查询_【赵强老师】MongoDB中的索引(下)
(四)索引的類型三:復合索引(Compound Index)
MongoDB支持復合索引,即將多個鍵組合到一起創(chuàng)建索引。該方式稱為復合索引,或者也叫組合索引,該方式能夠滿足多鍵值匹配查詢使用索引的情形。其次復合索引在使用的時候,也可以通過前綴法來使用索引。MongoDB中的復合索引與關系型數(shù)據(jù)庫基本上一致。在關系型數(shù)據(jù)庫中復合索引使用的一些原則同樣適用于MongoDB。
在前面的內容中,我們已經在emp集合上創(chuàng)建了一個復合索引,如下:
db.emp.createIndex({"deptno":1,"sal":-1})下面使用不同的過濾條件查詢文檔,查看相應的執(zhí)行計劃:
(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()(五)復合索引與排序
復合索引創(chuàng)建時按升序或降序來指定其排列方式。對于單鍵索引,其順序并不是特別重要,因為MongoDB可以在任一方向遍歷索引。對于復合索引,按何種方式排序能夠決定該索引在查詢中能否被使用到。
db.emp.createIndex({"deptno":1,"sal":-1})在前面的內容中,我們已經在deptno上按照升序、sal上按照降序建立了復合索引,下面測試不同的排序的下,是否執(zhí)行了索引:
使用了索引的情況: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()(七)小結
復合索引是基于多個鍵(列)上創(chuàng)建的索引
復合索引在創(chuàng)建的時候可以為其每個鍵(列)來指定排序方法
索引鍵列的排序方法影響查詢在排序時候的操作,方向一致或相反的才能被匹配
復合索引與前綴索引通常在匹配的情形下才能被使用
總結
以上是生活随笔為你收集整理的go mongodb排序查询_【赵强老师】MongoDB中的索引(下)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 技校毕业是什么学历_技校毕业是什么学历
- 下一篇: maskrcnn用于目标检测_用于目标检