你在做什麼對我很好,它應該工作。
但是,如果只有有限數量的totalcount
值,那麼您將得到一個看起來隨機的結果集。考慮一個集合,其中最totalcount
值是2:
現在我們通過totalcount
(只有靠totalcount
)排序是:
> t.find({}, :sort => ['totalcount', Mongo::DESCENDING]).each(&show)
totalcount = 2, other = 3
totalcount = 2, other = 2
totalcount = 2, other = 1
totalcount = 2, other = 4
totalcount = 1, other = 1
totalcount = 1, other = 4
現在我們應用:limit
這正好給我們留下只totalcount == 2
值:
> t.find({}, :sort => ['totalcount', Mongo::DESCENDING], :limit => 4).each(&show)
totalcount = 2, other = 3
totalcount = 2, other = 2
totalcount = 2, other = 1
totalcount = 2, other = 4
你注意到other
排序的樣子隨機的?但是,如果我們添加輔助排序關鍵字,我們將得到的東西看起來分類:
> t.find({}, :sort => [['totalcount', Mongo::DESCENDING], ['other', Mongo::ASCENDING]], :limit => 4).show(&each)
totalcount = 2, other = 1
totalcount = 2, other = 2
totalcount = 2, other = 3
totalcount = 2, other = 4
totalcount
聽起來似乎不會有那麼多的價值,並將至少是包含許多重複的值。應用:limit
後:sort
因此它可以很容易地選擇結果只有一個或兩個值爲totalcount
。如果沒有第二個排序鍵,即使它們(部分)排序,也可以得到看起來是隨機的結果。
無論何時您使用可具有重複值的排序鍵,您通常都希望包含一個輔助排序鍵,以便在主要組中對其進行合理排序。
感謝非常詳細的回覆老兄!當然,我的語法是正確的,但我有一個錯字錯誤 - 愚蠢的錯誤! – 2012-03-19 23:21:01