Mongoid: select embedded objects that fits number of options
I have got this structure
class House
include Mongoid::开发者_高级运维Document
embeds_many :inhabitants
end
class Inhabitant
include Mongoid::Document
embedded_in :house
field :name
field :gender
field :age
end
I can get all houses where females live:
houses = House.where("inhabitants.gender" => "female")
But how can I get all houses where females under age 50 live? How can I specify more than one condition for embedded object?
To apply multiple conditions to each entry in an array, you should use the $elemMatch
operator. I'm not familiar with Mongoid, but here's the MongoDB shell syntax for your query modified to use $elemMatch
:
> db.house.find({inhabitants: {$elemMatch: {gender: "female", age: {$lt: 50}}}})
Try this:
houses = House.where("inhabitants.gender" => "female", "inhabitants.age" => {"$lt" => 50})
Combining conditions: MongoDB query:
db.houses.find({'inhabitants.age' : {$in: {$lt: 50}}})
Mongoid:
houses = House.where('inhabitants.age' => {'$in' => {'$lt' => 50}})
精彩评论