Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid query has_many

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.

like image 323
dboyd68 Avatar asked Mar 24 '23 01:03

dboyd68


1 Answers

Try this.

Subject.where(:course_id.in => @student.courses.map(&:id))
like image 115
Santhosh Avatar answered Mar 31 '23 14:03

Santhosh