2012-03-19 126 views
0

我有一個非常簡單的Mongodb集合,例如Ruby/Mongodb排序項降序

{ "_id" : ObjectId("objid"), "url" : "http://mydomain.com", "datestamp" : ISODate("2012-03-17T02:00:45.119Z"), "totalcount" : 1 } 

我想查詢集合降序排列如下返回項目:

@globallinks = Mongo::Connection.new.db("mydb").collection("mycollect") 
@toplinks = @globallinks.find({}, :sort => ["totalcount", Mongo::DESCENDING], :limit => 100) 

此查詢不返回倒序項目。通過掃描結果集,我知道一個事實,即記錄看起來是未排序的。

有沒有人有任何想法?

回答

2

你在做什麼對我很好,它應該工作。

但是,如果只有有限數量的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。如果沒有第二個排序鍵,即使它們(部分)排序,也可以得到看起來是隨機的結果。

無論何時您使用可具有重複值的排序鍵,您通常都希望包含一個輔助排序鍵,以便在主要組中對其進行合理排序。

+0

感謝非常詳細的回覆老兄!當然,我的語法是正確的,但我有一個錯字錯誤 - 愚蠢的錯誤! – 2012-03-19 23:21:01