def map_reduce(map, reduce, opts={})
map = BSON::Code.new(map) unless map.is_a?(BSON::Code)
reduce = BSON::Code.new(reduce) unless reduce.is_a?(BSON::Code)
raw = opts.delete(:raw)
hash = BSON::OrderedHash.new
hash['mapreduce'] = self.name
hash['map'] = map
hash['reduce'] = reduce
hash.merge! opts
if hash[:sort]
hash[:sort] = Mongo::Support.format_order_clause(hash[:sort])
end
result = @db.command(hash, command_options(opts))
unless Mongo::Support.ok?(result)
raise Mongo::OperationFailure, "map-reduce failed: #{result['errmsg']}"
end
if raw
result
elsif result["result"]
if result['result'].is_a? BSON::OrderedHash and result['result'].has_key? 'db' and result['result'].has_key? 'collection'
otherdb = @db.connection[result['result']['db']]
otherdb[result['result']['collection']]
else
@db[result["result"]]
end
else
raise ArgumentError, "Could not instantiate collection from result. If you specified " +
"{:out => {:inline => true}}, then you must also specify :raw => true to get the results."
end
end