可以使用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
我要退房的map-reduce,但我不能看到如何實現它的任何很好的例子。 – Ben
文檔中有一些示例。和互聯網上的許多博客文章。 –