One-to-Few (Embedded) vs One-to-Many (Referenced) Data Modeling
One-to-Few (Embedded) vs One-to-Many (Referenced) Data Modeling
In relational databases, normalization dictates splitting entities across multiple tables linked by foreign keys. In MongoDB, data modeling is governed by the golden rule: "Data that is accessed together should be stored together." Choosing between Embedding (Denormalization) and Referencing (Normalization) is the most crucial architectural decision in NoSQL system design.
1. The Three Cardinal Rules of MongoDB Data Modeling
- 1Rule 1: Favor embedding unless there is a compelling reason not to.
- 2Rule 2: Needing to access an object on its own is a compelling reason not to embed it.
- 3Rule 3: Avoid arrays that grow without bound (the 16 MB document size limit).
2. Approach 1: Embedding (Denormalization / Subdocuments)
When related data has a One-to-Few or One-to-Squillions relationship that is always retrieved together:
When to Embed:
- One-to-Few: A user has 2 or 3 shipping addresses; an article has 3 tags.
- Atomic Updates: Updating a parent and its subdocuments in a single atomic write operation without transactions.
- Read Performance: Fetching the parent retrieves all data in a single disk read without joins.
3. Approach 2: Referencing (Normalization / Document Links)
When data has a One-to-Many (Unbounded) or Many-to-Many relationship, or when child entities must be queried independently:
When to Reference:
- One-to-Squillions: A YouTube channel with 10,000,000 log events or comments. Embedding an unbounded array would quickly breach MongoDB's 16 MB maximum document size limit!
- Independent Queries: When child documents must be searched, filtered, and paginated on their own.
- Frequently Changing Data: Storing mutable shared entities in one place prevents having to update thousands of duplicate embedded copies.
Multiple Choice Questions
Query Population with .populate() & Multi-Level Population
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.