Schema design in MongoDB involves creating a structure for your documents that supports your application's requirements while maintaining flexibility and performance. Unlike traditional relational databases, MongoDB allows for schema flexibility while still providing validation capabilities.
Schema Design Patterns in MongoDB
Store different types of documents in the same collection.
// Example: Different types of products
{
_id: "product1",
type: "book",
title: "MongoDB Guide",
author: "John Doe",
isbn: "123-456-789"
}
{
_id: "product2",
type: "electronics",
name: "Laptop",
brand: "TechBrand",
specifications: {...}
}
Store attributes as key-value pairs for flexible schemas.
// Example: Product with dynamic attributes
{
_id: "product1",
name: "Smartphone",
attributes: [
{ key: "color", value: "Black" },
{ key: "storage", value: "128GB" },
{ key: "ram", value: "8GB" }
]
}
Group related data into buckets for efficient storage.
// Example: Time-series data
{
_id: "sensor_2025_01",
sensor_id: "sensor1",
month: "2025-01",
readings: [
{ timestamp: ISODate("2025-01-01"), value: 25 },
{ timestamp: ISODate("2025-01-02"), value: 26 }
]
}
Store hierarchical data efficiently.
// Example: Category hierarchy
{
_id: "electronics",
name: "Electronics",
path: "electronics",
children: ["laptops", "phones"]
}
{
_id: "laptops",
name: "Laptops",
path: "electronics.laptops",
parent: "electronics"
}
Define validation rules for your collections.
// Create collection with validation
db.createCollection("products", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "price", "category"],
properties: {
name: {
bsonType: "string",
description: "must be a string"
},
price: {
bsonType: "double",
minimum: 0,
description: "must be a positive number"
},
category: {
bsonType: "string",
description: "must be a string"
}
}
}
}
})
Handle schema changes over time.
// Example: Adding a new field
db.products.updateMany(
{ newField: { $exists: false } },
{ $set: { newField: "default value" } }
)
Migrate data to new schema versions.
// Example: Migrating data
db.products.find().forEach(function(doc) {
db.products.updateOne(
{ _id: doc._id },
{ $set: { newStructure: transformData(doc) } }
)
})
Now that you understand schema design, you can explore: