MongoDB 查詢分析

來源:互聯網
上載者:User

標籤:

MongoDB 查詢分析可以確保我們建議的索引是否有效,是查詢語句效能分析的重要工具。

MongoDB 查詢分析常用函數有:explain() 和 hint()。

使用 explain()

explain 操作提供了查詢資訊,使用索引及查詢統計等。有利於我們對索引的最佳化。

接下來我們在 users 集合中建立 gender 和 user_name 的索引:

>db.users.ensureIndex({gender:1,user_name:1})</p><p>現在在查詢語句中使用 explain :</p><pre>>db.users.find({gender:"M"},{user_name:1,_id:0}).explain()

以上的 explain() 查詢返回如下結果:

{   "cursor" : "BtreeCursor gender_1_user_name_1",   "isMultiKey" : false,   "n" : 1,   "nscannedObjects" : 0,   "nscanned" : 1,   "nscannedObjectsAllPlans" : 0,   "nscannedAllPlans" : 1,   "scanAndOrder" : false,   "indexOnly" : true,   "nYields" : 0,   "nChunkSkips" : 0,   "millis" : 0,   "indexBounds" : {      "gender" : [         [            "M",            "M"         ]      ],      "user_name" : [         [            {               "$minElement" : 1            },            {               "$maxElement" : 1            }         ]      ]   }}

現在,我們看看這個結果集的欄位:

  • indexOnly: 欄位為 true ,表示我們使用了索引。
  • cursor:因為這個查詢使用了索引,MongoDB中索引儲存在B樹結構中,所以這是也使用了BtreeCursor類型的遊標。如果沒有使用索引,遊標的類型是BasicCursor。這個鍵還會給出你所使用的索引的名稱,你通過這個名稱可以查看當前資料庫下的system.indexes集合(系統自動建立,由於儲存索引資訊,這個稍微會提到)來得到索引的詳細資料。
  • n:當前查詢返回的文檔數量。
  • nscanned/nscannedObjects:表明當前這次查詢一共掃描了集合中多少個文檔,我們的目的是,讓這個數值和返迴文檔的數量越接近越好。
  • millis:當前查詢所需時間,毫秒數。
  • indexBounds:當前查詢具體使用的索引。
使用 hint()

雖然MongoDB查詢最佳化工具一般工作的很不錯,但是也可以使用hints來強迫MongoDB使用一個指定的索引。

這種方法某些情形下會提升效能。 一個有索引的collection並且執行一個多欄位的查詢(一些欄位已經索引了)。

如下查詢執行個體指定了使用 gender 和 user_name 索引欄位來查詢:

>db.users.find({gender:"M"},{user_name:1,_id:0}).hint({gender:1,user_name:1})

可以使用 explain() 函數來分析以上查詢:

>db.users.find({gender:"M"},{user_name:1,_id:0}).hint({gender:1,user_name:1}).explain()

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.