Create a gist now

Instantly share code, notes, and snippets.

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}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment