9. Document Schema Design Patterns
Document databases like MongoDB and Firestore require a different approach to schema design. Instead of normalizing across tables, you design documents based on your access patterns. The key to document schema design is understanding that you design for your queries.
This module covers embedding vs. referencing, aggregation patterns, and document schema design best practices. You'll learn when to embed data, when to reference it, and how to avoid common anti-patterns.
Embedding vs. Referencing
Embedding is the most common pattern in document databases. You embed related data in a parent document. This provides excellent read performance because you fetch all data in one request. Embedding is ideal for one-to-one and one-to-many relationships where data is accessed together.
Referencing is used for many-to-many relationships or when data is accessed independently. It requires multiple queries but avoids duplication.
// Embedding: User with embedded posts (good for 1-to-few) { _id: ObjectId('...'), name: 'Alice', email: 'alice@example.com', posts: [ { title: 'First Post', content: 'Hello' }, { title: 'Second Post', content: 'Hi again' } ] } // Referencing: Separate collections (good for many-to-many) // users collection { _id: ObjectId('user123'), name: 'Alice', email: 'alice@example.com' } // posts collection { _id: ObjectId('post456'), userId: ObjectId('user123'), title: 'First Post', content: 'Hello' }
Common Document Patterns
- Aggregate Pattern: Store related data together in one document.
- Bucket Pattern: Group time-series data by time interval.
- Computed Pattern: Store pre-computed values for faster queries.
- Subset Pattern: Separate frequently accessed data from rarely accessed data.
Anti-Patterns to Avoid
- Unbounded Arrays: Arrays that grow without limit cause performance issues.
- Deep Nesting: Documents that are too deeply nested are hard to query.
- Polymorphic Collections: Mixed document types without clear discrimination.
- Over-Embedding: Embedding too much data leads to large documents.
Knowledge Check
Ready to test your understanding of 9. Document Schema Design Patterns?