Grouping results and summarizing a field in one query with Mongoid?
I'm trying to execute a more or less advanced query with Mongoid that basically gets metrics for a date range, groups them by day and then summarizes the values for each day, it should also tell me how many entries there are for each day.
I highly doubt this can be done with the active record part of Mongoid, but I don't know how to execute queries on the mongo driver directly.
My model:
class Metric
include Mongoid::Document
field :id_session, :type => Integer
field :metric, :type => Integer
field :value, :type => Integer
field :date, :type => Date
field :time, :type => Time
validates_numericality_of :value
validates_presence_of :id_session, :metric, :value
before_create :set_date
def set_date
self.time = Time.now
self.date = Date.now
end
end
I've been able to get the results groupe开发者_Python百科d by date simply by using Metric.distinct(:date), but I don't know how to do a sum and count of those results as I can't use that method on the results.
Any ideas? I prefer to stay within the Mongoid active record methods but if anyone knows how I can execute queries directly on the MongoDB driver that would help too.
Thanks!
Managed to get it working
result = Metric.collection.group(
['date'] , nil, {:count => 0, :value => 0}, "function(x, y) { y.count++; y.value += x.value }"
)
Credits go to the answer on this page
精彩评论