Model One-to-Many Relationships with Embedded Documents
Overview
This page describes a data model that uses embedded documents to describe one-to-manyrelationships between connected data.
Pattern
Consider the following example that maps patron and multiple addressrelationships. The example illustrates the advantage of embedding overreferencing if you need to view many data entities in context ofanother. In this one-to-many relationship between patron
andaddress
data, the patron
has multiple address
entities.
In the normalized data model, the address
documents contain areference to the patron
document.
- {
- _id: "joe",
- name: "Joe Bookreader"
- }
- {
- patron_id: "joe",
- street: "123 Fake Street",
- city: "Faketon",
- state: "MA",
- zip: "12345"
- }
- {
- patron_id: "joe",
- street: "1 Some Other Street",
- city: "Boston",
- state: "MA",
- zip: "12345"
- }
If your application frequently retrieves the address
data with thename
information, then your application needs to issue multiplequeries to resolve the references. A more optimal schema would be toembed the address
data entities in the patron
data, as in thefollowing document:
- {
- _id: "joe",
- name: "Joe Bookreader",
- addresses: [
- {
- street: "123 Fake Street",
- city: "Faketon",
- state: "MA",
- zip: "12345"
- },
- {
- street: "1 Some Other Street",
- city: "Boston",
- state: "MA",
- zip: "12345"
- }
- ]
- }
With the embedded data model, your application can retrieve thecomplete patron information with one query.