Mongoid:检索所有嵌入的文档

时间:2013-08-24 18:43:01

标签: ruby mongodb 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

我想要的是检索特定Photo的所有Person。是否存在mongoid / mongodb快捷方式或唯一的方法是迭代person.albums并将所有album.photos存储在新数组中?

感谢。

1 个答案:

答案 0 :(得分:4)

你有两种方法可以做到这一点,一种是通过Mongoid,它是AFAIK,它会给所有物体充气。 类似的东西:

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

或者你可以在Moped(驱动程序)中执行它,它只会返回一组照片。

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

在DB加载上,两者都没有任何区别,因为它们会产生相同的查询,唯一的区别是第一个将创建比第二个更多的对象。

相关问题