public
Created — forked from jnunemaker/group_sum.rb

  • Download Gist
group_sum.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
require 'rubygems'
require 'mongo'
require 'pp'
 
db = Mongo::Connection.new.db('testing')
db.collections.each { |c| c.remove }
 
articles = db['articles']
ratings = db['ratings']
 
article_id = articles.save(:title => 'Foo')
 
ratings.save(:article_id => article_id, :rating => 2)
ratings.save(:article_id => article_id, :rating => 3)
ratings.save(:article_id => article_id, :rating => 5)
 
keys = [:article_id]
query = {:article_id => article_id}
initial = {:sum => 0}
function = "function(doc, prev) { prev.sum += doc.rating; }"
pp ratings.group(keys, query, initial, function)
 
__END__
 
[{"article_id"=>$oid4be315c9a8de309439000001, "sum"=>10.0}]

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.