在MongoDB中一起使用$or和sort()時,查詢效能可能會很差

來源:互聯網
上載者:User

首先看一下操作過程:

mongos> db.find({ "user" : "jhon"}).sort({"name" : 
1}).limit(100).explain()
{
"cursor" : "BtreeCursor user_1",
"nscanned" : 10100,
"nscannedObjects" : 10100,
"n" : 100,
"scanAndOrder" : true,
"millis" : 116,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
"user" : [
[
"jhon",
"jhon"
]
]
}
}

Second, I do $or query with sort():
mongos> db.find({ "$or" : [ { "user" : "jhon"} , { "owner" :
"jhon"}]}).sort({"name" : 1}).limit(100).explain()
{
"cursor" : "BtreeCursor name_1",
"nscanned" : 1010090,
"nscannedObjects" : 1010090,
"n" : 100,
"millis" : 3800,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
"name" : [
[
{
"$minElement" : 1
},
{
"$maxElement" : 1
}
]
]
}
}

Last, I do $or query without sort():
mongos> db.find({ "$or" : [ { "user" : "jhon"} , { "owner" :
"jhon"}]}).limit(100).explain()
{
"cursor" : "BtreeCursor user_1",
"nscanned" : 100,
"nscannedObjects" : 100,
"n" : 100,
"millis" : 0,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
"user" : [
[
"jhon",
"jhon"
]
]
}
}

可以看出:

第一次查詢中, 單獨使用sort()時效能很好。

第二次查詢中,聯合使用了$or和sort()時,效能很差。

第三次查詢中,單獨使用$or,效能很好。

後來在官方論壇中提問,得知有一個bug:https://jira.mongodb.org/browse/SERVER-1205

將來會修改,今天先記錄一下。

論壇回複:

I believe the issue you are running into is expressed in this JIRA 
ticket: https://jira.mongodb.org/browse/SERVER-1205 

I believe the query optimizer is choosing to use the name index and 
walk it backwards. As it goes through the index it compares the user 
and owner attributes to your parameters and collects them in sorted 
order. As a result the nscanned objects is much larger than in the 
other two cases. 

I would vote up the issue to prioritize it. 

-Tyler

 

原帖地址:http://groups.google.com/group/mongodb-user/browse_thread/thread/58428702d9485b8/40d6db4604a95a69?lnk=gst&q=gen+liu+%24or#40d6db4604a95a69

 

註:如果查詢中使用了$or,並且查詢元素有索引的話,那麼也會使用該元素的索引的。換句話說,如果查詢中只有$or時(無sort時),不會出現這裡的問題。另外在使用$and和$or的組合時也發現了類似的問題。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.