Ruby on rails Mongoid:选择适合多个选项的嵌入对象
我有这个结构Ruby on rails Mongoid:选择适合多个选项的嵌入对象,ruby-on-rails,ruby,ruby-on-rails-3,mongodb,mongoid,Ruby On Rails,Ruby,Ruby On Rails 3,Mongodb,Mongoid,我有这个结构 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"
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岁以下女性居住的房子呢?如何为嵌入对象指定多个条件?请尝试以下操作:
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}})
要对数组中的每个条目应用多个条件,应使用
$elemMatch
运算符。我不熟悉Mongoid,但以下是用于查询的MongoDB shell语法,已修改为使用$elemMatch
:
> db.house.find({inhabitants: {$elemMatch: {gender: "female", age: {$lt: 50}}}})
我已经试过了。但这会搜索所有居民,而不是每个人。你想找到所有至少有一名50岁以下女性居住的房子吗?是的。实际上,我想知道如何通过多个选项获取嵌入对象。就是这样!谢谢Mongoid语法:
House.where({居民:{gender:{elemMatch'=>{gender:{gender:{gender:{gender:{elemMatch},age:{lt'=>50}}}})
Alternate Mongoid(Origin)语法:House.elem(居民:{gender:'female',:age.lt=>50})
@dcrosta我已经挣扎了两个小时了。。。谢谢你的解决方案。我也有类似的情况。