2013-05-31 40 views
0

在MongoDB中,我有以下簡單的查詢,並在postTime上有一個索引:-1。該收藏有100,237份文件。 explain()表示查詢完全被索引覆蓋。MongoDB索引不會減少nscannedObjects

爲什麼nScannedObjects是100,237?另外,即使我只對前5個結果感興趣,查詢時間也是455ms。

我做錯了什麼,或者這是MongoDB如何工作?有人可以解釋爲什麼索引查詢需要這麼長時間嗎?

謝謝:)萊斯

db.guestBookPost.find({ postTime : {$gte : 0}, $orderby : { "postTime" : -1}}, {_id:0, >postTime:1}).limit(5).explain() 
{ 
    "cursor" : "BtreeCursor postTime_-1", 
    "isMultiKey" : false, 
    "n" : 0, 
    "nscannedObjects" : 100237, 
    "nscanned" : 100237, 
    "nscannedObjectsAllPlans" : 200474, 
    "nscannedAllPlans" : 200474, 
    "scanAndOrder" : false, 
    "indexOnly" : true, 
    "nYields" : 0, 
    "nChunkSkips" : 0, 
    "millis" : 455, 
    "indexBounds" : { 
    "postTime" : [ 
      [ 
       1.7976931348623157e+308, 
       0 
      ] 
     ] 
    }, 
    "server" : "ip-10-245-26-151:27017" 
} 

回答

0

使用$orderby語法似乎是什麼導致它。您可以使用:

db.guestBookPost. 
    find({ postTime : {$gte : 0}}, {_id:0, >postTime:1}). 
    sort({postTime: -1}). 
    limit(5). 
    explain() 

或者:

db.guestBookPost. 
    find({ postTime : {$gte : 0}}, {_id:0, >postTime:1}). 
    _addSpecial("$orderBy", {postTime: -1}). 
    limit(5). 
    explain() 

,它會正常工作。我不確定爲什麼$ orderby語法不能正常工作,但是其中任何一種方法都可以解決這個問題。

+1

這是一個錯誤,你不能在功能函數中使用'$'運算符 – Sammaye

+0

謝謝,備用語法確實有效。我有另一個查詢問題,我將單獨發佈。 – Les