allow scope for reduce function in group
This commit is contained in:
parent
46a8f78ce5
commit
e6112703f3
|
@ -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 = <<EOS
|
||||
function () {
|
||||
var c = db[ns].find(condition);
|
||||
|
@ -352,13 +372,7 @@ function () {
|
|||
return {"result": map.values()};
|
||||
}
|
||||
EOS
|
||||
return @db.eval(Code.new(group_function,
|
||||
{
|
||||
"ns" => @name,
|
||||
"keys" => keys,
|
||||
"condition" => condition,
|
||||
"initial" => initial
|
||||
}))["result"]
|
||||
return @db.eval(Code.new(group_function, scope))["result"]
|
||||
end
|
||||
|
||||
# Rename this collection.
|
||||
|
|
|
@ -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
|
||||
|
||||
|
|
Loading…
Reference in New Issue