From b1b61d5c0b23a29ff6f9f09c8d960bf5e34eb072 Mon Sep 17 00:00:00 2001 From: Christos Trochalakis Date: Mon, 23 Nov 2009 10:04:48 +0200 Subject: [PATCH] Added support for map-reduce --- lib/mongo/collection.rb | 27 +++++++++++++++++++++++++++ test/test_collection.rb | 12 ++++++++++++ 2 files changed, 39 insertions(+) diff --git a/lib/mongo/collection.rb b/lib/mongo/collection.rb index b1c01bc..f0bb8c6 100644 --- a/lib/mongo/collection.rb +++ b/lib/mongo/collection.rb @@ -298,6 +298,33 @@ module Mongo @db.drop_collection(@name) end + def mapreduce(map, reduce, options={}) + case map + when Code + else + map = Code.new(map) + end + + case reduce + when Code + else + reduce = Code.new(reduce) + end + + hash = OrderedHash.new + hash['mapreduce'] = self.name + hash['map'] = map + hash['reduce'] = reduce + hash.merge! options + + result = @db.db_command(hash) + if result["ok"] == 1 + return @db[result["result"]] + else + raise Mongo::OperationFailure, "map-reduce failed: #{result['errmsg']}" + end + end + # Perform a query similar to an SQL group by operation. # # Returns an array of grouped items. diff --git a/test/test_collection.rb b/test/test_collection.rb index 8ecdf1e..2e3ff44 100644 --- a/test/test_collection.rb +++ b/test/test_collection.rb @@ -265,6 +265,18 @@ class TestCollection < Test::Unit::TestCase assert c.closed? end + def test_mapreduce + @@test << { "user_id" => 1 } + @@test << { "user_id" => 2 } + + m = "function() { emit(this.user_id, 1); }" + r = "function(k,vals) { return 1; }" + res = @@test.mapreduce(m, r); + assert res.find_one({"_id" => 1}) + assert res.find_one({"_id" => 2}) + + end + def test_saving_dates_pre_epoch begin @@test.save({'date' => Time.utc(1600)})