MongoDB — Schema Design
Design Principles
| Principle | Description |
|---|---|
| Embed related data | Keep together |
| Duplicate for reads | Optimize queries |
| Avoid deep nesting | Keep flat |
| Use references | For large data |
Embedding
// Good: Small, related data
{
name: "John",
address: {
street: "123 Main St",
city: "New York"
}
}
Referencing
// Good: Large or shared data
{
name: "John",
orderId: ObjectId("...")
}
Patterns
Attribute Pattern
{
name: "Phone",
attributes: {
color: "black",
storage: 128,
weight: 150
}
}
Bucket Pattern
{
userId: ObjectId("..."),
measurements: [
{ date: new Date(), value: 100 },
{ date: new Date(), value: 102 }
]
}
Mini Practice
- Design embedded schema
- Design referenced schema
- Use attribute pattern
- Use bucket pattern
Up Next
Continue with Relationships — document relationships.
Related Topics
Frequently Asked Questions about Schema Design
What is Schema Design in MongoDB?
Schema Design is a fundamental concept in MongoDB. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Schema Design?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Schema Design.
Why is Schema Design important in MongoDB?
Schema Design is essential for MongoDB development. Understanding this concept will help you write better code and solve real-world problems more effectively.