In MongoDB, how can I replicate this simple query using map/reduce in ruby?
Posted
by Matthew Rathbone
on Stack Overflow
See other posts from Stack Overflow
or by Matthew Rathbone
Published on 2010-06-16T21:15:36Z
Indexed on
2010/06/16
22:12 UTC
Read the original article
Hit count: 265
Hi,
So using the regular MongoDB library in Ruby I have the following query to find average filesize across a set of 5001 documents:
avg = 0
total = collection.count()
Rails.logger.info "#{total} asset creation stats in the system"
collection.find().each {|row| avg += (row["filesize"] * (1/total.to_f)) if row["filesize"]}
Its pretty simple, so I'm trying to do the same using map/reduce as a learning exercise. This is what I came up with:
map = 'function(){emit("filesizes", {size: this.filesize, num: 1});}'
reduce = 'function(k, vals){
var result = {size: 0, num: 0};
for(var x in vals) {
var new_total = result.num + vals[x].num;
result.num = new_total
result.size = result.size + (vals[x].size * (vals[x].num / new_total));
}
return result;
}'
@results = collection.map_reduce(map, reduce)
However the two queries come back with two different results!
What am I doing wrong?
© Stack Overflow or respective owner