SyntaxStudy
Sign Up
MongoDB Schema Design Patterns
MongoDB Beginner 1 min read

Schema Design Patterns

Even though MongoDB is schema-flexible, thoughtful schema design is critical for performance and maintainability. The bucket pattern groups related time-series or sequence data into single documents (for example, one document per hour of IoT sensor readings) to reduce document count and improve range query performance. The extended reference pattern embeds a small, frequently-accessed subset of a referenced document to avoid $lookup joins on hot read paths. The outlier pattern handles the rare case where an array could grow very large by moving overflow elements to separate documents linked by a flag. The attribute pattern converts a varying set of key-value pairs into an array of objects, making heterogeneous fields queryable with a single index.
Example
// BUCKET PATTERN — one document per hour for IoT sensor data
{
  _id: ObjectId(),
  deviceId: "sensor_42",
  date: ISODate("2024-03-15T14:00:00Z"),
  // 60 readings packed in one document instead of 60 documents
  readings: [
    { minute: 0,  temp: 22.1, humidity: 45 },
    { minute: 1,  temp: 22.3, humidity: 44 },
    // ... up to minute 59
  ],
  count: 60,
  avgTemp: 22.5
}

// ATTRIBUTE PATTERN — index heterogeneous product specs
{
  _id: ObjectId(),
  name: "4K Monitor",
  // Instead of top-level fields (resolution, refreshRate, panelType)
  // use an array of key-value pairs — one index covers all attributes
  specs: [
    { k: "resolution",   v: "3840x2160" },
    { k: "refreshRate",  v: 144 },
    { k: "panelType",    v: "IPS" }
  ]
}

// Index for the attribute pattern
db.products.createIndex({ "specs.k": 1, "specs.v": 1 })

// Query: find all monitors with 144Hz refresh rate
db.products.find({ specs: { $elemMatch: { k: "refreshRate", v: 144 } } })