MongoDB 覆蓋索引查詢

來源:互聯網
上載者:User

標籤:

MongoDB 覆蓋索引查詢

官方的MongoDB的文檔中說明,覆蓋查詢是以下的查詢:

  • 所有的查詢欄位是索引的一部分
  • 所有的查詢返回欄位在同一個索引中

由於所有出現在查詢中的欄位是索引的一部分, MongoDB 無需在整個資料文檔中檢索匹配查詢條件和返回使用相同索引的查詢結果。

因為索引存在於RAM中,從索引中擷取資料比通過掃描文檔讀取資料要快得多。

為了測試蓋索引查詢,使用以下 mycol 集合:

{ "_id" : 1, "name" : "tom", "sex" : "男", "score" : 100, "age" : 34 }
{ "_id" : 2, "name" : "jeke", "sex" : "男", "score" : 90, "age" : 24 }
{ "_id" : 3, "name" : "kite", "sex" : "女", "score" : 40, "age" : 36 }
{ "_id" : 4, "name" : "herry", "sex" : "男", "score" : 90, "age" : 56 }
{ "_id" : 5, "name" : "marry", "sex" : "女", "score" : 70, "age" : 18 }
{ "_id" : 6, "name" : "john", "sex" : "男", "score" : 100, "age" : 31 }

我們在 users 集合中建立聯合索引,欄位為 sex 和 score :

db.mycol.ensureIndex({sex : 1, score : 1})

現在,該索引會覆蓋以下查詢:

db.mycol.find({sex: ‘男‘},{name : 1, _id : 0})

 

也就是說,對於上述查詢,MongoDB的不會去資料庫檔案中尋找。相反,它會從索引中提取資料,這是非常快速的資料查詢。

由於我們的索引中不包括 _id 欄位,_id在查詢中會預設返回,我們可以在MongoDB的查詢結果集中排除它。

下面的執行個體沒有排除_id,查詢就不會被覆蓋:

db.mycol.find({sex: ‘男‘},{name : 1})

 

最後,如果所有索引欄位是一個數組,不能使用覆蓋索引查詢。

 








MongoDB 覆蓋索引查詢

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.