Mongoid-按参考文件查询 [英] Mongoid - querying by referenced document
问题描述
我有一个名为Ad的模型,它看起来像这样:
I have a model named Ad which looks like this:
class Ad
include Mongoid::Document
referenced_in :category
end
和类别模型:
class Category
include Mongoid::Document
referenced_in :domain
references_many :ads
end
如何选择按域分类的广告?
我尝试使用Ad.where('category.domain_id' => domain.id)
,但这不起作用.
How can I select Ads by domain?
I have tried to use Ad.where('category.domain_id' => domain.id)
but this does not work.
推荐答案
问题是MongoDB无法将Category
记录映射到Ad
记录.它所知道的就是Ad
记录具有category_id
字段,因此'category.domain_id'
将始终不返回任何内容.查询中的点符号仅适用于嵌入式文档,不适用于引用(在MongoDB中仍是二等公民).
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).
因此,要解决您的问题,您将需要2个查询:
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)
这篇关于Mongoid-按参考文件查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!