Skip to content

Instantly share code, notes, and snippets.

@jvmvik
Last active November 21, 2016 13:06
Show Gist options
  • Select an option

  • Save jvmvik/8f0967486e904175faec to your computer and use it in GitHub Desktop.

Select an option

Save jvmvik/8f0967486e904175faec to your computer and use it in GitHub Desktop.
Ruby mongoDB map reduce
# Ruby mongoDB map reduce
# The mongoDB documentation missed totally to
# describes a simple usage for map reduce in Ruby.
# and the web is full of misleading example based on the previous API.
#
# This gist try to fill out the gap.
# First please read https://docs.mongodb.org/manual/tutorial/map-reduce-examples/
# below it is a simple Ruby implementation.
#
# @doc https://docs.mongodb.org/manual/core/map-reduce/
# @example https://docs.mongodb.org/manual/tutorial/map-reduce-examples/
# @date 20 March 2016
# @author vikoky
#
# Tools
# ---
# Ruby 2.2.1
# MongoDB drive 2.2.0
# Mongo 2.6
#
mapFunc = %q(
var mapFunction1 = function() {
emit(this.product_id, {price: this.price});
};
)
reduceFunc = %q(
var reduceFunction1 = function(keyCustId, values)
{
var a = values[0]; // will reduce into here
for (var i=1; i < values.length; i++)
{
var b = values[i];
a.price += b.price;
}
return a;
};
)
# Connect to mongoDB
db = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'example')
db[:product].insert_one( { product_id: 0, price: 20 } )
db[:product].insert_one( { product_id: 0, price: 30 } )
db[:product].insert_one( { product_id: 1, price: 10 } )
# Prepare Map Reduce
mr = db[:product].find().map_reduce(mapFunc, reduceFunc)
mr.out(inline: 1)
mr.verbose(true)
# Execute/Display results
p mr.to_a
# or
mr.each do |doc|
p doc
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment