2013-08-24 126 views
3

假設我們有這些模型:Mongoid:檢索所有嵌入文檔

class Person 
    include Mongoid::Document 

    embeds_many :albums 
end 

class Album 
    include Mongoid::Document 

    embeds_many :photos 
end 

class Photo 
    include Mongoid::Document 
end 

我想要的是檢索特定Person的所有Photo。是否有一個mongoid/mongodb快捷方式或唯一的方法是迭代person.albums並將所有album.photos存儲在一個新數組中?

謝謝。

回答

4

你有兩種方法可以做到這一點,一種是通過Mongoid,AFAIK將膨脹所有對象。 喜歡的東西:

Person.only("albums.photos").where(id: '1').albums.map(&:photos).flatten 

或者你可以在助力車(驅動器)將返回唯一的照片數組做到這一點。

Person.collection.find(id: "1").select("albums.photos" => 1). 
first["albums"].map { |a| a["photos"] }.flatten 

在DB負荷,既不要讓任何區別,因爲它們將得到相同的查詢,唯一的區別是第一個將創造比第二單向多個對象。

+0

在第二種情況下,照片將是「照片」或「哈希」? – Iazel

+0

第二種情況你將只有哈希值。 –