使用Mongoid分组结果并汇总一个查询中的字段?
问题描述:
我试图用Mongoid执行一个或多或少的高级查询,它基本上获取日期范围的度量标准,将它们按天分组,然后总结每天的值,它也应该告诉我每个项目有多少条目天。使用Mongoid分组结果并汇总一个查询中的字段?
我非常怀疑这可以用Mongoid的活动记录部分来完成,但我不知道如何直接在mongo驱动程序上执行查询。
我的模型:
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
我已经能够简单地通过使用Metric.distinct度日日期分组的结果(:日期),但我不知道如何做一个总和计数这些结果因为我无法在结果中使用该方法。
任何想法?我更喜欢留在Mongoid活动记录方法中,但是如果有人知道我可以直接在MongoDB驱动上执行查询,那也会有帮助。
谢谢!
答
设法得到它的工作
result = Metric.collection.group(
['date'] , nil, {:count => 0, :value => 0}, "function(x, y) { y.count++; y.value += x.value }"
)
现金去答案的this page