diff --git a/lib/mongo/collection.rb b/lib/mongo/collection.rb index 2cfecfb..8b7e149 100644 --- a/lib/mongo/collection.rb +++ b/lib/mongo/collection.rb @@ -314,10 +314,17 @@ module Mongo keys.each do |k| hash[k] = 1 end + + case reduce + when Code + else + reduce = Code.new(reduce) + end + result = @db.db_command({"group" => { "ns" => @name, - "$reduce" => Code.new(reduce), + "$reduce" => reduce, "key" => hash, "cond" => condition, "initial" => initial}}) @@ -327,6 +334,19 @@ module Mongo raise OperationFailure, "group command failed: #{result['errmsg']}" end end + + case reduce + when Code + scope = reduce.scope + else + scope = {} + end + scope.merge!({ + "ns" => @name, + "keys" => keys, + "condition" => condition, + "initial" => initial }) + group_function = < @name, - "keys" => keys, - "condition" => condition, - "initial" => initial - }))["result"] + return @db.eval(Code.new(group_function, scope))["result"] end # Rename this collection. diff --git a/test/test_collection.rb b/test/test_collection.rb index 2db3a8c..aa1eb7f 100644 --- a/test/test_collection.rb +++ b/test/test_collection.rb @@ -186,5 +186,36 @@ class TestCollection < Test::Unit::TestCase assert_equal nil, @@test.find_one(:foo => "mike") assert_equal nil, @@test.find_one("foo" => "mike") end + + def test_group_with_scope + @@test.save("a" => 1) + @@test.save("b" => 1) + + reduce_function = "function (obj, prev) { prev.count += inc_value; }" + + assert_equal 2, @@test.group([], {}, {"count" => 0}, + Code.new(reduce_function, + {"inc_value" => 1}))[0]["count"] + +# TODO enable these tests when SERVER-262 is fixed + +# assert_equal 2, @@test.group([], {}, {"count" => 0}, +# Code.new(reduce_function, +# {"inc_value" => 1}), true)[0]["count"] + + assert_equal 4, @@test.group([], {}, {"count" => 0}, + Code.new(reduce_function, + {"inc_value" => 2}))[0]["count"] +# assert_equal 4, @@test.group([], {}, {"count" => 0}, +# Code.new(reduce_function, +# {"inc_value" => 2}), true)[0]["count"] + + assert_equal 1, @@test.group([], {}, {"count" => 0}, + Code.new(reduce_function, + {"inc_value" => 0.5}))[0]["count"] +# assert_equal 1, @@test.group([], {}, {"count" => 0}, +# Code.new(reduce_function, +# {"inc_value" => 0.5}), true)[0]["count"] + end end