I have a fairly simple mongodb model Currently 2 collections Student Courses (embeds Subjects)
class Student < User
include Mongoid::Document
has_many :courses
class Course
include Mongoid::Document
belongs_to :student
embeds_many :subjects
I know mongoid doesn't support querying has_many directly i.e.
Student.courses
So if I wanted to get a students subject is this the only way
@student = Student.first
Course.find(@student.courses).subjects
This currently does 3 queries
MOPED: 127.0.0.1:27017 QUERY database=test collection=users selector= {"$query"=>{"_type"=>{"$in"=>["Student"]}}, "$orderby"=>{:_id=>1}} flags=[:slave_ok] limit=-1 skip=0 batch_size=nil fields=nil (1.1775ms)
MOPED: 127.0.0.1:27017 QUERY database=test collection=courses selector={"student_id"=>"51f09457b5b605db25000002"} flags=[:slave_ok] limit=0 skip=0 batch_size=nil fields=nil (0.8862ms)
MOPED: 127.0.0.1:27017 QUERY database=test collection=courses selector={"_id"=>"51f09457b5b605db25000003"} flags=[:slave_ok] limit=0 skip=0 batch_size=nil fields=nil (0.8380ms)
Is there a more efficient way? I know I can embed Course in Student but I looking at also querying directly into Courses Collection.
Try this.
Subject.where(:course_id.in => @student.courses.map(&:id))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With