Model One-to-Many Relationships with Document References
Data in MongoDB has a flexible schema. Collections do not enforce document structure. Decisions that affect how you model data can affect application performance and database capacity. See Data Modeling Concepts for a full high level overview of data modeling in MongoDB.
This document describes a data model that uses references between documents to describe relationships between connected data.
Consider the following example that maps publisher and book relationships. The example illustrates the advantage of referencing over embedding to avoid repetition of the publisher information.
Embedding the publisher document inside the book document would lead to repetition of the publisher data, as the following documents show:
To avoid repetition of the publisher data, use references and keep the publisher information in a separate collection from the book collection.
When using references, the growth of the relationships determine where to store the reference. If the number of books per publisher is small with limited growth, storing the book reference inside the publisher document may sometimes be useful. Otherwise, if the number of books per publisher is unbounded, this data model would lead to mutable, growing arrays, as in the following example:
To avoid mutable, growing arrays, store the publisher reference inside the book document: