Data modeling patterns
Named patterns such as subset, bucket, computed and extended reference solve common modelling problems.
In this page:
Data modeling patterns
The subset pattern embeds only the most-used part of a big array. The bucket pattern groups time-series items into one document per period.
The computed pattern stores precomputed totals, and the extended reference copies a few fields from another document to avoid joins.
Note:
Precompute what you read often and update it on write.
Example: Data modeling patterns
// Bucket pattern: one document per sensor per hour instead of one per reading
test> db.readings.insertOne({ _id: "s1-2024010510", sensor: "s1", count: 0, sum: 0, values: [] })
{ acknowledged: true, insertedId: 's1-2024010510' }
test> db.readings.updateOne({ _id: "s1-2024010510" }, { $push: { values: 21.5 }, $inc: { count: 1, sum: 21.5 } })
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
test> db.readings.updateOne({ _id: "s1-2024010510" }, { $push: { values: 22.5 }, $inc: { count: 1, sum: 22.5 } })
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
test> db.readings.aggregate([{ $project: { _id: 0, sensor: 1, count: 1, avg: { $divide: ["$sum", "$count"] } } }])
[ { sensor: 's1', count: 2, avg: 22 } ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Copying too many fields
- Never refreshing computed values
- Using patterns before measuring need
Chapter Summary
- Subset embeds the hot part
- Bucket groups time-series data
- Computed stores totals
- Extended reference copies key fields
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: