首先看一下操作過程:
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的組合時也發現了類似的問題。