MongoDB
 sql >> Teknologi Basis Data >  >> NoSQL >> MongoDB

Cara terbaik untuk mengelompokkan berdasarkan tanggal dengan Mongoid

Inilah jawaban yang menggunakan kerangka kerja agregasi untuk mengelompokkan berdasarkan tanggal. Saya harap Anda menyukainya.

app/model/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, op| [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

test/unit/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", "created_at" => Date.new(2012, 10, 31).mongoize},
        {"name" => "Mary", "created_at" => Date.new(2012, 10, 31).mongoize},
        {"name" => "Mark", "created_at" => Date.new(2012, 12, 12).mongoize},
        {"name" => "Alex", "created_at" => Date.new(2013, 11, 10).mongoize},
        {"name" => "Andy", "created_at" => Date.new(2013, 10, 31).mongoize},
        {"name" => "Toni", "created_at" => Date.new(2013, 10, 31).mongoize},
        {"name" => "Cori", "created_at" => Date.new(2013, 11, 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

$ menyapu tes

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, "month"=>10}, "count"=>2},
 {"_id"=>{"year"=>2013, "month"=>11}, "count"=>2},
 {"_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



  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. Konsistensi baca-Anda-tulis-tulis di Mongodb

  2. Menghubungkan ke MongoDB Atlas menggunakan Golang mgo:Persistent no reachable server to replika set

  3. Perbedaan antara basis data berbasis Dokumen dan Basis Data Kunci/Nilai?

  4. Kueri agregat Mongodb pada catatan tertentu alih-alih koleksi

  5. pengambilan referensi mongoDB membutuhkan waktu