Model One-to-Many Relationships with Document References

Overview

This page describes a data model that uses references between documents to describe one-to-manyrelationships between connected data.

Pattern

Consider the following example that maps publisher and bookrelationships. The example illustrates the advantage of referencingover embedding to avoid repetition of the publisher information.

Embedding the publisher document inside the book document would lead torepetition of the publisher data, as the following documents show:

  1. {
  2. title: "MongoDB: The Definitive Guide",
  3. author: [ "Kristina Chodorow", "Mike Dirolf" ],
  4. published_date: ISODate("2010-09-24"),
  5. pages: 216,
  6. language: "English",
  7. publisher: {
  8. name: "O'Reilly Media",
  9. founded: 1980,
  10. location: "CA"
  11. }
  12. }
  13.  
  14. {
  15. title: "50 Tips and Tricks for MongoDB Developer",
  16. author: "Kristina Chodorow",
  17. published_date: ISODate("2011-05-06"),
  18. pages: 68,
  19. language: "English",
  20. publisher: {
  21. name: "O'Reilly Media",
  22. founded: 1980,
  23. location: "CA"
  24. }
  25. }

To avoid repetition of the publisher data, use references and keepthe publisher information in a separate collection from the bookcollection.

When using references, the growth of the relationships determine whereto store the reference. If the number of books per publisher is smallwith limited growth, storing the book reference inside the publisherdocument may sometimes be useful. Otherwise, if the number of books perpublisher is unbounded, this data model would lead to mutable, growingarrays, as in the following example:

  1. {
  2. name: "O'Reilly Media",
  3. founded: 1980,
  4. location: "CA",
  5. books: [123456789, 234567890, ...]
  6. }
  7.  
  8. {
  9. _id: 123456789,
  10. title: "MongoDB: The Definitive Guide",
  11. author: [ "Kristina Chodorow", "Mike Dirolf" ],
  12. published_date: ISODate("2010-09-24"),
  13. pages: 216,
  14. language: "English"
  15. }
  16.  
  17. {
  18. _id: 234567890,
  19. title: "50 Tips and Tricks for MongoDB Developer",
  20. author: "Kristina Chodorow",
  21. published_date: ISODate("2011-05-06"),
  22. pages: 68,
  23. language: "English"
  24. }

To avoid mutable, growing arrays, store the publisher reference insidethe book document:

  1. {
  2. _id: "oreilly",
  3. name: "O'Reilly Media",
  4. founded: 1980,
  5. location: "CA"
  6. }
  7.  
  8. {
  9. _id: 123456789,
  10. title: "MongoDB: The Definitive Guide",
  11. author: [ "Kristina Chodorow", "Mike Dirolf" ],
  12. published_date: ISODate("2010-09-24"),
  13. pages: 216,
  14. language: "English",
  15. publisher_id: "oreilly"
  16. }
  17.  
  18. {
  19. _id: 234567890,
  20. title: "50 Tips and Tricks for MongoDB Developer",
  21. author: "Kristina Chodorow",
  22. published_date: ISODate("2011-05-06"),
  23. pages: 68,
  24. language: "English",
  25. publisher_id: "oreilly"
  26. }