Model Many-to-Many Relationships with Embedded Documents
Create a data model that uses embedded documents to describe a many-to-many relationship between connected data. Embedding connected data in a single document can reduce the number of read operations required to obtain data. In general, structure your schema so your application receives all of its required information in a single read operation. For example, you can use the embedded many-to-many model to describe the following relationships:
Students to classes
Actors to movies
Doctors to patients
About this Task
The following example schema contains information regarding book one
and book two
and their authors. You can represent the relationship
differently based on whether you anticipate application users querying by
book or by author.
If you expect more users to query by book than by author, the example schema is an effective choice. However, if you expect more queries by author, make the author the top-level information and place the author's books in an embedded field.
Example
You can use a many-to-many relationship to describe books and authors. A book can have multiple authors, and an author can write multiple books.
Embedded Document Pattern
The application needs to display information for the book and author objects on a single page. To allow your application to retrieve all necessary information with a single query, embed author information inside of the corresponding book document:
{ _id: "book001", title: "Cell Biology", authors: [ { author_id: "author124", name: "Ellie Smith" }, { author_id: "author381", name: "John Palmer" } ] } { _id: "book002", title: "Organic Chemistry", authors: [ { author_id: "author290", name: "Jane James" }, { author_id: "author381", name: "John Palmer" } ] }