title: Aggregate functions with MongoDB/Mongoid and calculated fields
body: <p>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.</p>
  
  <p>Previously I had something like <code>SELECT DATE(created_at) AS day, SUM(amount) AS amount GROUP BY day</code>, Which would return a collection that you can loop through in the template like this:</p>
  
  <pre><code>:day =&gt; '2011-03-01', :amount =&gt; 55.00 
  :day =&gt; '2011-03-02', :amount =&gt; 45.00
  etc...
  </code></pre>
  
  <p>Does anyone know how to do that in Mongoid? The model is pretty straightforward:</p>
  
  <pre><code>class Conversion
    include Mongoid::Document
    include Mongoid::Timestamps
  
    field :amount,      :type =&gt; Float, :default =&gt; 0.0
    ...
    # created_at generated automatically, standard Rails...
  end
  </code></pre>
  
  <p>Thanks!</p>
  
  <p>-Avishai</p>