Schema Design Patterns
Designing flexible yet efficient MongoDB schemas
Skills taught: mongodb.schema
Schema Design in MongoDB
Even though MongoDB is schema-flexible, good schema design is critical for performance. In SQL, you normalize data into tables to avoid duplication. In MongoDB, you design around your query patterns — sometimes duplicating data intentionally to make reads faster.
The golden rule: data that is accessed together should be stored together. If you always load a blog post with its author's name, consider embedding the author's name inside the post document instead of doing a separate lookup.
Embedding vs Referencing
Embedding vs Referencing
- Embedding: Store related data inside the same document as a nested object or array
- Referencing: Store the _id of related documents and look them up separately
// EMBEDDING — 1-to-few (order with its items)
// Good: items belong only to this order, always loaded together
{
_id: ObjectId(),
orderId: 'ORD-001',
customerId: ObjectId('...'),
items: [ // embedded array — OK for small, bounded arrays
{ sku: 'ABC', qty: 2, price: 999 },
{ sku: 'XYZ', qty: 1, price: 299 }
],
total: 2297,
status: 'confirmed'
}
// REFERENCING — 1-to-many (user with their orders)
// Bad to embed: a user could have thousands of orders over time
{
_id: ObjectId(),
email: 'alice@example.com',
name: 'Alice'
// orders: [...] — DON'T embed, can grow unboundedly!
// Instead, store userId in each order document
}
// Orders collection — reference back to user
{
_id: ObjectId(),
userId: ObjectId('...'), // reference to users collection
total: 2297,
placedAt: new Date()
}
Common Schema Patterns
Pattern 1: Extended Reference (Denormalization)
Instead of referencing and joining, copy frequently-read fields from the referenced document into the parent. This avoids a join at read time.
// Pure reference — requires $lookup to get author name
{
_id: ObjectId(),
title: 'MongoDB Schema Design',
authorId: ObjectId('...') // must $lookup users collection
}
// Extended reference — author name copied in for fast reads
{
_id: ObjectId(),
title: 'MongoDB Schema Design',
author: {
_id: ObjectId('...'), // keep _id for linking
name: 'Alice Sharma', // copied from users — no join needed!
avatar: '/avatars/alice.jpg'
}
// Note: if Alice changes her name, you must update this too
}
Pattern 2: Computed Pattern
Pre-compute and store frequently-read aggregated values to avoid expensive real-time aggregation.
// Instead of computing average rating on every page load:
// SELECT AVG(rating) FROM reviews WHERE productId = '...'
// Store the computed values in the product document:
{
_id: ObjectId(),
name: 'Wireless Headphones',
price: 2499,
// Pre-computed aggregates — updated whenever a review is added
ratings: {
average: 4.3,
count: 128,
sum: 550.4 // kept for recalculation accuracy
}
}
// When a new review is added, update atomically:
await products.updateOne(
{ _id: productId },
{
$inc: { 'ratings.count': 1, 'ratings.sum': newRating },
$set: { 'ratings.average': (currentSum + newRating) / (currentCount + 1) }
}
);
Pattern 3: Bucket Pattern (Time-Series)
Group time-series data into time buckets (e.g., one document per hour per sensor) to reduce document count and enable efficient range queries.
// BAD: one document per measurement — millions of tiny documents
{ sensorId: 'S1', timestamp: ISODate('2026-11-12T10:00:01Z'), temp: 22.5 }
{ sensorId: 'S1', timestamp: ISODate('2026-11-12T10:00:02Z'), temp: 22.6 }
// ... millions more
// GOOD: bucket pattern — one document per hour per sensor
{
sensorId: 'S1',
date: ISODate('2026-11-12T10:00:00Z'), // hour bucket start
count: 3600,
measurements: [
{ ts: ISODate('2026-11-12T10:00:01Z'), temp: 22.5 },
{ ts: ISODate('2026-11-12T10:00:02Z'), temp: 22.6 },
// up to 3600 entries per document
],
stats: { min: 22.1, max: 23.4, avg: 22.7 } // computed
}
// Result: 24 documents per sensor per day instead of 86,400!
Warning: Never store unbounded arrays in a document — arrays that grow forever will eventually hit MongoDB's 16MB document limit. If a list can grow beyond ~1000 items, use referencing or the bucket pattern instead.
Tip: MongoDB provides a native Time Series collection type (since 5.0) that automatically applies the bucket pattern for you. Consider using it for IoT sensor data or analytics events instead of building the bucket pattern manually.
Frequently Asked Questions
Can a MongoDB document have size limits?
Yes. A single BSON document cannot exceed 16 MB. For large arrays that grow over time (like all comments on a popular post), use referencing (store post_id in each comment) or the bucket pattern rather than embedding.
Should I normalize my data like SQL, or denormalize in MongoDB?
MongoDB favors denormalization (embedding related data) for read-heavy workloads. Duplication is acceptable when it means avoiding slow joins. However, if the same data needs to be updated in many places, referencing is better to avoid consistency problems.
Does MongoDB enforce schema rules?
Not by default, but you can use JSON Schema validation on a collection: db.createCollection('users', { validator: { $jsonSchema: { ... } } }). This lets you require certain fields and enforce types while still allowing flexibility.