加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 使用Mongoid按日期分组的最佳方式

发布时间:2020-12-17 03:37:42 所属栏目:百科 来源:网络整理
导读:我正在尝试使用不同的格式(日,月,年)按日期进行查询分组,我知道这对于典型的SQL数据库来说是一个简单的查询. 您可以在此链接上看到代码:https://gist.github.com/jrdi/b3f824fa4e7531c43bfd 知道我可以跑: Patient.group_by('created_at','day')= [{"_id":
我正在尝试使用不同的格式(日,月,年)按日期进行查询分组,我知道这对于典型的SQL数据库来说是一个简单的查询.

您可以在此链接上看到代码:https://gist.github.com/jrdi/b3f824fa4e7531c43bfd

知道我可以跑:

> Patient.group_by('created_at','day')
=> [{"_id":"11/10/2013","value":{"count":3.0}}]

在我看来,所有这些代码组成一个简单的组是非常奇怪的.我错过了重要的事吗?

PD:我知道方法self.map和一些插值不是最好的方法,但知道我关心Mongo的东西.

解决方法

这是一个使用聚合框架按日期分组的答案.我希望你喜欢它.

应用程序/模型/ patient.rb

class Patient
  include Mongoid::Document
  field :name,type: String

  def self.group_by(field,format = 'day')
    key_op = [['year','$year'],['month','$month'],['day','$dayOfMonth']]
    key_op = key_op.take(1 + key_op.find_index { |key,op| format == key })
    project_date_fields = Hash[*key_op.collect { |key,op| [key,{op => "$#{field}"}] }.flatten]
    group_id_fields = Hash[*key_op.collect { |key,"$#{key}"] }.flatten]
    pipeline = [
        {"$project" => {"name" => 1,field => 1}.merge(project_date_fields)},{"$group" => {"_id" => group_id_fields,"count" => {"$sum" => 1}}},{"$sort" => {"count" => -1}}
    ]
    collection.aggregate(pipeline)
  end
end

测试/单元/ patient_test.rb

require 'test_helper'
require 'pp'

class PatientTest < ActiveSupport::TestCase
  def setup
    Patient.delete_all
  end

  test "group by date" do
    [
        {"name" => "John","created_at" => Date.new(2012,10,10).mongoize},{"name" => "Jane",31).mongoize},{"name" => "Mary",{"name" => "Mark",12,12).mongoize},{"name" => "Alex","created_at" => Date.new(2013,11,{"name" => "Andy",{"name" => "Toni",{"name" => "Cori",10).mongoize}
    ].each do |patient|
      Patient.create(patient)
    end
    puts "nMongoid::VERSION:#{Mongoid::VERSION}nMoped::VERSION:#{Moped::VERSION}"
    pp Patient.group_by('created_at','month')
  end
end

$rake test

Run options:

# Running tests:

[1/1] PatientTest#test_group_by_date
Mongoid::VERSION:3.1.5
Moped::VERSION:1.5.1
[{"_id"=>{"year"=>2012,"month"=>10},"count"=>3},{"_id"=>{"year"=>2013,"count"=>2},"month"=>11},{"_id"=>{"year"=>2012,"month"=>12},"count"=>1}]
Finished tests in 0.042561s,23.4957 tests/s,0.0000 assertions/s.
1 tests,0 assertions,0 failures,0 errors,0 skips

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读