Appearance
MongoDB Document Modeling
Embed vs Reference
Rule of thumb:
Embed if:
- ✅ One-to-few (user has 1 address)
- ✅ Data accessed together (user profile + preferences)
- ✅ Bounded array size (ví dụ minh hoạ: vài chục đến ~100 phần tử; đo kích thước document thật, trần cứng 16 MiB)
- ✅ Data evolves together (update user = update preferences)
Reference if:
- ✅ One-to-many (user has 1000 orders)
- ✅ Data accessed independently (view user without orders)
- ✅ Unbounded growth (comments on viral post)
- ✅ Many-to-many (products ← orders → users)
Pattern 1: Embedded Documents (Denormalization)
javascript
// mongosh
// User with embedded address (one-to-one)
db.users.insertOne({
name: "John Doe",
email: "john@example.com",
address: { // Embedded document
street: "123 Main St",
city: "San Francisco",
zip: "94102"
},
preferences: { // Embedded document
theme: "dark",
notifications: true
}
})
// Query: Get user with address in 1 query
db.users.findOne({ email: "john@example.com" })
// Update: Atomic update
db.users.updateOne(
{ email: "john@example.com" },
{ $set: { "address.city": "New York" }}
)Pros:
- ✅ 1 query (not 2)
- ✅ Atomic updates
- ✅ Faster reads
Cons:
- ❌ Kích thước document (tối đa 16 MiB, lồng tối đa 100 cấp BSON, mỗi object/array là một cấp)
- ❌ Duplication if shared
Pattern 2: Embedded Array (One-to-Few)
javascript
// mongosh
// Product with reviews (bounded array)
db.products.insertOne({
name: "Laptop",
price: 999,
reviews: [ // Embedded array (<100 reviews)
{ userId: 123, rating: 5, comment: "Great!" },
{ userId: 456, rating: 4, comment: "Good value" }
]
})
// Query: Get product with reviews
db.products.findOne({ name: "Laptop" })
// Add review: $push
db.products.updateOne(
{ name: "Laptop" },
{ $push: { reviews: { userId: 789, rating: 5, comment: "Excellent" }}}
)Limit array size:
javascript
// mongosh, chạy sau khối Product with reviews ở trên
// Keep only latest 100 reviews
db.products.updateOne(
{ name: "Laptop" },
{
$push: {
reviews: {
$each: [{ userId: 789, rating: 5 }],
$slice: -100 // Keep last 100
}
}
}
)Pattern 3: References (Normalization)
javascript
// mongosh
db.users.insertOne({
_id: ObjectId("665f1c2a9b1e4a0012345678"),
name: "John Doe",
email: "john@example.com"
})
// Order documents (separate collection)
db.orders.insertOne({
userId: ObjectId("665f1c2a9b1e4a0012345678"), // Reference to user
total: 99.99,
status: "completed"
})
// Query: Get user
db.users.findOne({ _id: ObjectId("665f1c2a9b1e4a0012345678") })
// Query: Get user's orders (separate query)
db.orders.find({ userId: ObjectId("665f1c2a9b1e4a0012345678") })
// Or use $lookup (join)
db.users.aggregate([
{ $match: { _id: ObjectId("665f1c2a9b1e4a0012345678") }},
{ $lookup: {
from: "orders",
localField: "_id",
foreignField: "userId",
as: "orders"
}}
])Pros:
- ✅ No duplication
- ✅ Unbounded growth (1M orders OK)
- ✅ Independent updates
Cons:
- ❌ 2 queries (or slow $lookup)
- ❌ Cross-collection atomicity needs multi-document transactions (supported since 4.0, extra cost)
Pattern 4: Bucket Pattern (Time-Series)
Problem: IoT sensor sends 1 reading/second → 86,400 documents/day → too many documents
Solution: Use a native time series collection (MongoDB 5.0+, buckets automatically); manual hourly bucketing only for older versions
text
// minh hoạ hình dạng document, không chạy độc lập
// Bad: 1 document per reading
{
_id: ObjectId("..."),
sensorId: "sensor123",
timestamp: ISODate("2025-01-09T10:00:00Z"),
temperature: 25.5
}
// → 86,400 docs/day/sensor
// Good: Bucket 1 hour of readings
{
_id: ObjectId("..."),
sensorId: "sensor123",
date: ISODate("2025-01-09T10:00:00Z"), // Hour bucket
readings: [
{ timestamp: ISODate("2025-01-09T10:00:00Z"), temperature: 25.5 },
{ timestamp: ISODate("2025-01-09T10:00:01Z"), temperature: 25.6 },
// ... 3,600 readings (1 hour)
],
count: 3600,
avgTemp: 25.7
}
// → 24 docs/day/sensor (3,600x reduction)Time series collection (thay cho bucket tự làm):
javascript
// mongosh (MongoDB 5.0+): time series collection, server tự gom bucket
db.createCollection("readings", {
timeseries: { timeField: "timestamp", metaField: "sensorId", granularity: "seconds" }
})
db.readings.insertMany([
{ sensorId: "sensor123", timestamp: ISODate("2025-01-09T10:00:00Z"), temperature: 25.5 },
{ sensorId: "sensor123", timestamp: ISODate("2025-01-09T10:00:01Z"), temperature: 25.6 }
])
db.readings.aggregate([
{ $group: { _id: "$sensorId", avgTemp: { $avg: "$temperature" } } }
])Benefits:
- ✅ Fewer documents (better index performance)
- ✅ Pre-aggregated stats (avgTemp)
- ✅ Easier retention (drop old buckets)
Pattern 5: Outlier Pattern
Problem: Most users have <10 orders, but some power users have 10,000+
Solution: Embed small arrays, reference large arrays
text
// minh hoạ hình dạng document, không chạy độc lập
// Normal user (few orders - embedded)
{
_id: ObjectId("user123"),
name: "John",
orders: [
{ orderId: "order001", total: 99 },
{ orderId: "order002", total: 149 }
],
hasOverflowOrders: false
}
// Power user (many orders - referenced)
{
_id: ObjectId("user456"),
name: "Power User",
orders: [
{ orderId: "order001", total: 99 },
// ... first 100 orders embedded
],
hasOverflowOrders: true // ← Flag
}
// Overflow collection
{
_id: ObjectId("..."),
userId: ObjectId("user456"),
orders: [
{ orderId: "order101", total: 49 },
// ... remaining orders
]
}Pattern 6: Computed Pattern
Problem: Aggregating review ratings on every product view is slow
Solution: Pre-compute and store
javascript
// mongosh
db.products.insertOne({
_id: "product123",
name: "Laptop",
reviews: [],
stats: { // Computed/cached
ratingSum: 0,
reviewCount: 0,
avgRating: null,
ratingDistribution: { "5": 0, "4": 0, "3": 0, "2": 0, "1": 0 }
}
})
// Update stats on new review (single atomic write; the pipeline recomputes the average)
db.products.updateOne(
{ _id: "product123" },
[
{ $set: {
reviews: { $concatArrays: ["$reviews", [{ rating: 5, comment: "Great" }]] },
"stats.reviewCount": { $add: ["$stats.reviewCount", 1] },
"stats.ratingSum": { $add: ["$stats.ratingSum", 5] },
"stats.ratingDistribution.5": { $add: ["$stats.ratingDistribution.5", 1] }
}},
{ $set: { "stats.avgRating": { $round: [{ $divide: ["$stats.ratingSum", "$stats.reviewCount"] }, 2] } } }
]
)Pattern 7: Subset Pattern
Problem: Product has 10,000 reviews, but users only see top 10
Solution: Embed subset, reference full data
text
// minh hoạ hình dạng document, không chạy độc lập
{
_id: ObjectId("product123"),
name: "Laptop",
topReviews: [ // Embedded (top 10)
{ rating: 5, comment: "Best laptop!", helpful: 1200 },
{ rating: 5, comment: "Excellent", helpful: 980 },
// ... top 10 by helpfulness
],
stats: {
totalReviews: 10543
}
}
// Full reviews in separate collection
// reviews collection: { productId: ObjectId("product123"), ... }Pattern 8: Extended Reference Pattern
Problem: Need some fields from related document frequently (e.g., order → user name)
Solution: Duplicate frequently accessed fields
javascript
// mongosh
// Order with extended reference to user
db.orders.insertOne({
userId: ObjectId("665f1c2a9b1e4a0012345678"),
userName: "John Doe", // Duplicated from users collection
userEmail: "john@example.com", // Duplicated
total: 99.99,
status: "pending"
})
// Query orders: Get user name without join
db.orders.find({ status: "pending" })
// → Returns userName directly (no $lookup)Trade-off:
- ✅ Faster reads (no join)
- ❌ Duplication (update both if user name changes)
Phải nhớ:
- Nhúng khi dữ liệu đọc cùng nhau và có chặn trên; tham chiếu khi tăng không chặn. Trần cứng: document 16 MiB, lồng 100 cấp BSON.
- Dữ liệu chuỗi thời gian: dùng time series collection (MongoDB 5.0+) thay cho bucket tự làm.
- Extended reference đổi bản sao lấy đọc nhanh: lên kế hoạch cập nhật cả hai nơi.