MongoDB
Beginner
1 min read
Schema Design Patterns
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 } } })