I’m migrating an existing Rails app to use MongoDB (with Mongoid), and I’m having some trouble figuring out how to do aggregations like you can do with MySQL.
Previously I had something like SELECT DATE(created_at) AS day, SUM(amount) AS amount GROUP BY day, Which would return a collection that you can loop through in the template like this:
:day => '2011-03-01', :amount => 55.00
:day => '2011-03-02', :amount => 45.00
etc...
Does anyone know how to do that in Mongoid? The model is pretty straightforward:
class Conversion
include Mongoid::Document
include Mongoid::Timestamps
field :amount, :type => Float, :default => 0.0
...
# created_at generated automatically, standard Rails...
end
Thanks!
-Avishai
Unfortunately, it’s a bit harder than you would think.
My understanding is that Mongoid itself does not support grouping and addition in one query, to do so – you’ll need to do a map/reduce directly with the MongoDB driver. I ran this example with a similar data structure to what you have, but there may be a couple of errors during the translation, if you have any trouble, let me know and i’ll try and amend it.
First you need to define your map and reduce functions. These have to be stored as JavaScript strings.
Then you call
map_reducedirectly on the collection, in this case:Which will return an array of hashes like the following: