Skip to content

Instantly share code, notes, and snippets.

@fredrikhenne
Forked from jnunemaker/group_sum.rb
Created May 6, 2010 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fredrikhenne/392594 to your computer and use it in GitHub Desktop.
Save fredrikhenne/392594 to your computer and use it in GitHub Desktop.
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