2012-05-27 36 views
0

我工作的一個簡單的項目,我有兩個樣品參考模型的發生:怎麼算的參考模型在MongoDB中/ Mongoid

class Player 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    has_and_belongs_to_many :games 
end 

class Game 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    has_and_belongs_to_many :players 
end 

我需要做的就是上面的列表與玩家數量一起玩遊戲。此類似:

{ 
    "diablo_3": { 
    "players": 89 
    }, 
    "max_payne_3": { 
    "players": 87 
    }, 
    "world_of_warcraft": { 
    "players": 65 
    }, 
    "dirt_3": { 
    "players": 43 
    } 
} 

感謝

+0

我要退房的map-reduce,但我不能看到如何實現它的任何很好的例子。 – Ben

+0

文檔中有一些示例。和互聯網上的許多博客文章。 –

回答

1

可以使用MongoDB的group命令做一些服務器的尺寸加工的單個集合, 它可作爲Ruby驅動程序上收集的方法, 請參閱http://api.mongodb.org/ruby/current/Mongo/Collection.html#group-instance_method

下面請根據您的模型找到一個測試,標題字段添加到您的遊戲模型中。 這是對使用MongoDB組命令的問題的一個工作答案。

require 'test_helper' 

class GameTest < ActiveSupport::TestCase 
    def setup 
    Player.delete_all 
    Game.delete_all 
    end 

    test "game player count" do 
    input = [ [ 'diablo_3', 89 ], [ 'max_payne_3', 87 ], [ 'world_of_warcraft', 65 ], [ 'dirt_3', 43 ] ] 
    input.shuffle.each do | title, count | 
     game = Game.create(title: title) 
     (0...count).each{ game.players << Player.new } 
    end 
    game_player_count = Game.collection.group(key: :_id, cond: {}, initial: {count: 0}, reduce: 'function(doc, out) { out.title = doc.title; out.count = doc.player_ids.length; }') 
    game_player_count.sort!{|a,b| -(a['count'] <=> b['count']) } 
    game_player_count = Hash[*game_player_count.map{|r| [r['title'], {"players" => r['count'].to_i} ]}.flatten] 
    puts JSON.pretty_generate(game_player_count) 
    end 

end 

結果

Run options: --name=test_game_player_count 

# Running tests: 

{ 
    "diablo_3": { 
    "players": 89 
    }, 
    "max_payne_3": { 
    "players": 87 
    }, 
    "world_of_warcraft": { 
    "players": 65 
    }, 
    "dirt_3": { 
    "players": 43 
    } 
} 
. 

Finished tests in 0.482286s, 2.0735 tests/s, 0.0000 assertions/s. 

1 tests, 0 assertions, 0 failures, 0 errors, 0 skips 
+0

謝謝加里。我會測試你的片段在我身邊。 :-) – Ben

+0

謝謝Gary的幫助。 – Ben

+0

很高興能有所幫助。希望你在享受Mongoid/MongoDB。 –