我有这个结构
class House
include Mongoid::Document
embeds_many :inhabitants
end
class Inhabitant
include Mongoid::Document
embedded_in :house
field :name
field :gender
field :age
end
我可以得到所有女性居住的房屋:
houses = House.where("inhabitants.gender" => "female")
但我如何才能获得50岁以下女性居住的所有房屋?如何为嵌入对象指定多个条件?
答案 0 :(得分:7)
要将多个条件应用于数组中的每个条目,您应该使用$elemMatch
运算符。我不熟悉Mongoid,但是这里的MongoDB shell语法被修改为使用$elemMatch
的查询:
> db.house.find({inhabitants: {$elemMatch: {gender: "female", age: {$lt: 50}}}})
答案 1 :(得分:-1)
试试这个:
houses = House.where("inhabitants.gender" => "female", "inhabitants.age" => {"$lt" => 50})
合并条件: MongoDB查询:
db.houses.find({'inhabitants.age' : {$in: {$lt: 50}}})
Mongoid:
houses = House.where('inhabitants.age' => {'$in' => {'$lt' => 50}})