使用 Mongoid 对一个查询中的结果进行分组并汇总字段?

发布于 2024-10-14 01:28:01 字数 821 浏览 0 评论 0原文

我正在尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

脸赞 2024-10-21 01:28:01

设法让它工作

    result = Metric.collection.group(
  ['date'] , nil, {:count => 0, :value => 0}, "function(x, y) { y.count++; y.value += x.value }"
)

积分转到

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文