go mongodb排序查询_「赵强老师」MongoDB中的索引(下)
(四)索引的類型三:復(fù)合索引(Compound Index)**
MongoDB支持復(fù)合索引,即將多個(gè)鍵組合到一起創(chuàng)建索引。該方式稱為復(fù)合索引,或者也叫組合索引,該方式能夠滿足多鍵值匹配查詢使用索引的情形。其次復(fù)合索引在使用的時(shí)候,也可以通過(guò)前綴法來(lái)使用索引。MongoDB中的復(fù)合索引與關(guān)系型數(shù)據(jù)庫(kù)基本上一致。在關(guān)系型數(shù)據(jù)庫(kù)中復(fù)合索引使用的一些原則同樣適用于MongoDB。
在前面的內(nèi)容中,我們已經(jīng)在emp集合上創(chuàng)建了一個(gè)復(fù)合索引,如下:
db.emp.createIndex({"deptno":1,"sal":-1})下面使用不同的過(guò)濾條件查詢文檔,查看相應(yīng)的執(zhí)行計(jì)劃:
(1)僅使用deptno作為過(guò)濾條件
db.emp.find({"deptno":10}).explain()(2)使用deptno、sal作為過(guò)濾條件
db.emp.find({"deptno":10,"sal":3000}).explain()(3)使用deptno、sal作為過(guò)濾條件,但把sal放在前面
db.emp.find({"sal":3000,"deptno":10}).explain()(4)僅使用sal作為過(guò)濾條件
db.emp.find({"sal":3000}).explain()(五)復(fù)合索引與排序
復(fù)合索引創(chuàng)建時(shí)按升序或降序來(lái)指定其排列方式。對(duì)于單鍵索引,其順序并不是特別重要,因?yàn)镸ongoDB可以在任一方向遍歷索引。對(duì)于復(fù)合索引,按何種方式排序能夠決定該索引在查詢中能否被使用到。
db.emp.createIndex({"deptno":1,"sal":-1})在前面的內(nèi)容中,我們已經(jīng)在deptno上按照升序、sal上按照降序建立了復(fù)合索引,下面測(cè)試不同的排序的下,是否執(zhí)行了索引:
使用了索引的情況:db.emp.find().sort({"deptno":1,"sal":-1}).explain()db.emp.find().sort({"deptno":-1,"sal":1}).explain()沒(méi)有使用索引的情況:db.emp.find().sort({"deptno":1,"sal":1}).explain()db.emp.find().sort({"deptno":-1,"sal":-1}).explain()交換兩個(gè)列的位置,再進(jìn)行測(cè)試。(六)復(fù)合索引與索引前綴
索引前綴指的是復(fù)合索引的子集,假如存在如下索引:
db.emp.createIndex({"deptno":1,"sal":-1,"job":1})那么就存在以下的索引前綴:{"deptno":1}{"deptno":1,"sal":-1}在MongoDB中,下列查詢過(guò)濾條件情形中,索引將會(huì)被使用到:
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()下列查詢過(guò)濾條件情形中,索引將不會(huì)被使用到:
db.emp.find().sort({deptno:1,job:1}).explain()db.emp.find().sort({sal:-1,job:1}).explain()(七)小結(jié)
- 復(fù)合索引是基于多個(gè)鍵(列)上創(chuàng)建的索引
- 復(fù)合索引在創(chuàng)建的時(shí)候可以為其每個(gè)鍵(列)來(lái)指定排序方法
- 索引鍵列的排序方法影響查詢?cè)谂判驎r(shí)候的操作,方向一致或相反的才能被匹配
- 復(fù)合索引與前綴索引通常在匹配的情形下才能被使用
總結(jié)
以上是生活随笔為你收集整理的go mongodb排序查询_「赵强老师」MongoDB中的索引(下)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python拷贝文件函数_Python
- 下一篇: 牡蛎家常做法?