← Back to MongoDB Course | Chapter 9: Schema Design | Lesson 4 of 7

Data modeling patterns

Named patterns such as subset, bucket, computed and extended reference solve common modelling problems.

In this page:

  1. Data modeling patterns

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

bash
// 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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Copying too many fields
  2. Never refreshing computed values
  3. 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

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.