Reputation: 1416
I have a class model, a student model and an attendance model. Attendance is embedded in Student to improve the performance.
I want to show number of all students in Class, number of present students, number of absent student & percentage of attendance. I am a newbie in Mongodb and i would appreciate any help. Thanks you for your time.
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
Upvotes: 0
Views: 1369
Reputation: 7405
You can try these:
@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
Upvotes: 1
Reputation: 1416
I have solved my problem by following technique.
@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
Upvotes: 1