使用 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(:date) 获得按日期分组的结果,但我不知道如何对这些结果进行求和和计数,因为我无法使用该方法关于结果。
有什么想法吗?我更喜欢留在 Mongoid 活动记录方法中,但如果有人知道如何直接在 MongoDB 驱动程序上执行查询,那也会有帮助。
谢谢!
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 grouped 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
设法让它工作
积分转到
Managed to get it working
Credits go to the answer on this page