Embedded documents
As the name suggests, documents embedded inside other documents are called embedded documents. When the parent document is fetched, it also fetches all the embedded documents. This is similar to the composition concept.
The following code shows how we can define an embedded document:
class Address
include Mongoid::Document
field :street, type: String
field :city, type: String
field :state, type: String
field :zipcode, type: String
field :country, type: String
embedded_in :author
end
And the following code denotes how we can embed it into another model:
class Author
include Mongoid::Document
field :name, type: String
has_many :books
embeds_one :address
end
Now let's have a quick look at how this information was stored in the database. As it was an embedded document, when we fetched the author object, we also got the author's address.
> db.authors.findOne() { "_id" : ObjectId("5143678345db7ca255000001"), "address" : { "_id" : ObjectId("514367f445db7ca255000003...