MongoDB โ Data Modeling & Schema Design
Master the principles of MongoDB schema design. Learn William Zola's 6 Rules of Thumb, when to embed sub-documents vs reference ObjectIds, and common design patterns.
1Embedding vs Referencing: The Golden Rule
The central question in MongoDB schema design is: Should I embed related data inside a single document or store it in a separate collection using ObjectId references?
๐ก The Core Rule:
Data that is accessed together should be stored together. Embed by default unless there is a compelling reason to reference.
2William Zola's 6 Rules of Thumb for Schema Design
- Rule 1: Favor embedding unless there is a compelling reason not to.
- Rule 2: Needed-together access is the best reason to embed fields.
- Rule 3: One-to-Few relationships (e.g., user addresses) should be EMBEDDED.
- Rule 4: One-to-Many relationships (e.g., product reviews) should use REFERENCES if array growth is unbounded.
- Rule 5: One-to-Squillions (e.g., server log streams) should store parent reference ID on the child document.
- Rule 6: How you query data dictates how you structure your data.
3Practical Relationship Modeling Patterns
Embedded 1:N (Addresses inside User)
// User Document (Embedded Addresses)
{
"_id": ObjectId("..."),
"name": "Balaji",
"addresses": [
{ "type": "home", "city": "Hyderabad" },
{ "type": "office", "city": "Bengaluru" }
]
}
Referenced 1:N (Parent ID on Child Document)
// Order Document referencing User ID
{
"_id": ObjectId("..."),
"userId": ObjectId("65d8f1e2a9b3c4d5e6f7a8b9"), // Reference to User
"totalAmount": 249.99,
"orderDate": ISODate("2026-08-26")
}