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.

  1. {
  2. _id: "joe",
  3. name: "Joe Bookreader"
  4. }
  5.  
  6. {
  7. patron_id: "joe",
  8. street: "123 Fake Street",
  9. city: "Faketon",
  10. state: "MA",
  11. zip: "12345"
  12. }
  13.  
  14. {
  15. patron_id: "joe",
  16. street: "1 Some Other Street",
  17. city: "Boston",
  18. state: "MA",
  19. zip: "12345"
  20. }

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:

  1. {
  2. _id: "joe",
  3. name: "Joe Bookreader",
  4. addresses: [
  5. {
  6. street: "123 Fake Street",
  7. city: "Faketon",
  8. state: "MA",
  9. zip: "12345"
  10. },
  11. {
  12. street: "1 Some Other Street",
  13. city: "Boston",
  14. state: "MA",
  15. zip: "12345"
  16. }
  17. ]
  18. }

With the embedded data model, your application can retrieve thecomplete patron information with one query.