简体   繁体   中英

Mongoid - querying by referenced document

I have a model named Ad which looks like this:

class Ad
  include Mongoid::Document
  referenced_in :category
end

and Category model:

class Category
  include Mongoid::Document
  referenced_in :domain
  references_many :ads
end

How can I select Ads by domain? I have tried to use Ad.where('category.domain_id' => domain.id) but this does not work.

The problem is that MongoDB doesn't have any way of mapping a Category record to an Ad record. All it knows is that an Ad record has a category_id field so 'category.domain_id' will always return nothing. The dot notation inside queries works only for embedded documents, not references (which are still second-class citizens in MongoDB).

So to solve your problem, you'll need 2 queries:

category_ids = Category.where(:domain_id => domain.id).map(&:_id)
Ad.where(:category_id.in => category_ids)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM