2013-07-27 90 views
2

我需要爲8個用戶中的每一個獲取前3個結果。目前我正在爲每個用戶循環播放,並將8個呼叫作爲分貝。有沒有一種方法來構建查詢以在單個數據庫拉取中提取相同的8X3數據集?MongoDB複雜查找

selected_users = users.sample(8) 
cur = 0 
while cur <= selected_users .count-1 
    cursor = status_store.find({'user' => selected_users[cur]},{:fields =>params}).sort('score', -1).limit(3) 
    *do something* 
    cur+=1 
end 

我正在拉的集合看起來像下面。每個用戶都可以擁有無​​限數量的推文,所以我沒有將它們嵌入到用戶文檔中。

{ 
    "_id" : ObjectId("51e92cc8e1ce7219e40003eb"), 
    "id_str" : "57915476419948544", 
    "score" : 904, 
    "text" : "Yesterday we had a bald eagle on the show. Oddly enough, he was in the country illegally.", 
    "timestamp" : "19/07/2013 08:10", 
    "user" : { 
      "id_str" : "115485051", 
      "name" : "Conan O'Brien", 
      "screen_name" : "ConanOBrien", 
      "description" : "The voice of the people. Sorry, people.", 
    } 
} 

在此先感謝。

+0

由於您沒有提供太多架構等方面的知識,所以很難說。通常,您可以使用'$ in'來獲取多個文檔。 – WiredPrairie

+1

你絕對應該閱讀[聚合框架](http://docs.mongodb.org/manual/core/aggregation/)它可以解決你的問題 – evilive

+0

甚至有一個雙[$組,限制3,ruby示例](https ://github.com/mongodb/mongo-ruby-driver/wiki/Aggregation-Framework-Examples)在GitHub上。 – arober11

回答

0

是的,你可以使用aggregation framework來做到這一點。

另一種方法是跟蹤用戶文檔中的前3個分數。如果這個更快或者更低,取決於你寫分數的頻率和用戶閱讀的最高分數。