Reputation: 2336
Suppose we have these models:
class Person
include Mongoid::Document
embeds_many :albums
end
class Album
include Mongoid::Document
embeds_many :photos
end
class Photo
include Mongoid::Document
end
What I want is to retrieves all Photo
of a particular Person
. Is there a mongoid/mongodb shortcuts or the only way is to iterate over person.albums
and store all album.photos
in a new array?
Thanks.
Upvotes: 3
Views: 1780
Reputation: 12128
You have 2 ways to do this, one is through Mongoid, which, AFAIK, will inflate all objects. Something like:
Person.only("albums.photos").where(id: '1').albums.map(&:photos).flatten
Or you can do it in Moped(driver) which will return only an array of photos.
Person.collection.find(id: "1").select("albums.photos" => 1).
first["albums"].map { |a| a["photos"] }.flatten
On the DB load, both dont make any difference, as they will yield the same query, only difference is that the first one will create way more objects than the second one.
Upvotes: 4