如何查询 rails & mongoid 中的嵌入文档

How to query embedded document in rails & mongoid

我有一个 class 模型,一个学生模型和一个出勤模型。出勤被嵌入到学生中以提高性能。

我想显示 Class 中所有学生的人数、在校学生人数、缺席学生人数和出勤率。我是 Mongodb 的新手,如果有任何帮助,我将不胜感激。谢谢你的时间。

class Klass
  include Mongoid::Document
  include Mongoid::Timestamps

  has_and_belongs_to_many :students

  field :name, type: String
end

class Student
  include Mongoid::Document
  include Mongoid::Timestamps

  has_and_belongs_to_many :klasses
  embeds_many :attendances

  field :name, type: String
end

class Attendance
  include Mongoid::Document
  include Mongoid::Timestamps

  embedded_in :student

  field :status, type: Integer # 1 = Present, 2 = Absent
  field :klass_id, type: BSON::ObjectId
end

你可以试试这些:

@class = Klass.where(name: 'something').first

@total_students = @class.students.count

@present_students = @class.students.where('attendances.status' => '1').count

@absent_students = @class.students.where('attendances.status' => '2').count

@p_s_today = @class.students.where('attendances.status' => '1', 'attendances.created_at' => {'$gte' => Date.today} ).count

@a_s_today = @class.students.where('attendances.status' => '2', 'attendances.created_at' => {'$gte' => Date.today} ).count

我已经通过以下技巧解决了我的问题。

@students_present_today = @class.students.where({ attendances: { '$elemMatch' => {status: 1, :created_at.gte => Date.today} } }).count
@students_absent_today = @class.students.where({ attendances: { '$elemMatch' => {status: 2, :created_at.gte => Date.today} } }).count