1
快速實例,軌mongoid發現帶子女的單親
class Band
include Mongoid::Document
embeds_many :albums
end
class Album
include Mongoid::Document
field :name, type: String
embedded_in :band
end
和文檔看起來就像這樣,
{
"_id" : ObjectId("4d3ed089fb60ab534684b7e9"),
"albums" : [
{
"_id" : ObjectId("4d3ed089fb60ab534684b7e0"),
"name" : "Violator",
}
]
}
可以說,我想打一個方法來查找Band with albums name
如果這是ActiveRecord
,那很簡單
Album.find_by(name: "Violator").band
但是這樣的情況呢?
我必須迭代整個集合,並找到它是這樣嗎?
Band.select {|band| band.albums.select{|album| album.name == "Violator"}}
聽起來很瘋狂......
還是我必須做Referenced relations
不Embedded relations
數據建模?
這裏有更多的細節我說你要獲得與樂隊' Band.where(「albums.name」=>「Violator」)'然後迭代已過濾的樂隊 – apneadiving
,但是您肯定會在嵌入內容的限制下,多推一點,然後您會開始質疑nosql – apneadiving