2011-09-12 48 views
3

我有這種結構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" => "female") 

但我怎麼能得到所有的房子裏女性50歲以下生活?我如何爲嵌入對象指定多個條件?

回答

6

要應用多個條件中的每個條目以陣列,你應該使用$elemMatch運營商。我不熟悉Mongoid,但這裏是您的查詢修改爲使用的MongoDB shell語法$elemMatch

> db.house.find({inhabitants: {$elemMatch: {gender: "female", age: {$lt: 50}}}}) 
+0

就是這樣!謝謝! Mongoid語法:'House.where {{居民:{「$ elemMatch」=> {性別:「女性」,年齡:{「$ lt」=> 50}}}})' – fl00r

+0

替代的Mongoid(Origin)語法:'' House.elem_match(居民:{性別:'女性',:age.lt => 50}) – colllin

+0

@dcrosta我一直在掙扎最後2個小時......感謝您的解決方案。我有類似的情況。 – JVK

-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}}) 
+0

我已經試過這個。但是這會搜索所有居民,而不是通過每個居民。 – fl00r

+0

您想取得所有至少有1名50歲以下女性居住的房屋? – Hck

+0

yeap。其實我想知道如何通過嵌入對象獲取多個選項。 – fl00r