to obtain a mongoïd model in nest of rings

advertisements

2 models:

Class User
 include Mongoid::Document
 has_many :reports
end

Class Report
 include Mongoid::Document
 belongs_to :user
end

I need a query to get all users have 6 or more reports, something like:.

Users.where(reports.count > 5)

I use mongo id 2.4.12

How can I do it?

Thank you very much!


Ok, This query is not possible since MongoDB does not have joins.

The fix for this problem is use a counter cache.

The first option is make a counter cache something like:

class User
  include Mongoid::Document
  field :reports_count, type: Integer
  has_many :reports
end

class Report
  include Mongoid::Document
  belongs_to :user
  after_create do |doc|
    doc.user.inc(:reports_count, 1)
  end
  after_destroy do |doc|
    doc.user.inc(:reports_count, -1)
  end
end

The second option (I have used this option) is use this gem https://github.com/jah2488/mongoid-magic-counter-cache.

For this question:

Models:

class User
 include Mongoid::Document
 field :report_count
 has_many :reports
end

Class Report
 include Mongoid::Document
 include Mongoid::MagicCounterCache
 belongs_to :user
 end

Inside a helper for example:

def users_with_reports_greather_than_5
 users_with_reports_greather_than_5 = []
 for u in User.where(report_count.ne => nil)
  if u.report_count > 5
   users_with_reports_greather_than_5 << u
  end
 end
 return users_with_reports_greather_than_5.count
end

Regards!