MongoDB Schema Design

Introduction to Schema Design

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.

MongoDB Schema Design

Schema Design Patterns in MongoDB

Schema Design Patterns

Polymorphic Pattern

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: {...}
}

Attribute Pattern

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" }
    ]
}

Bucket Pattern

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 }
    ]
}

Tree Pattern

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"
}

Schema Validation

Document Validation

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"
                }
            }
        }
    }
})

Validation Levels

  • strict: All documents must pass validation
  • moderate: Only new and modified documents are validated
  • off: No validation is performed

Implementation Strategies

Schema Evolution

Handle schema changes over time.

// Example: Adding a new field
db.products.updateMany(
    { newField: { $exists: false } },
    { $set: { newField: "default value" } }
)

Data Migration

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) } }
    )
})

Best Practices

Design Guidelines

  • Start with a flexible schema
  • Add validation as your schema stabilizes
  • Consider query patterns when designing
  • Use appropriate data types
  • Implement proper indexing
  • Plan for schema evolution

Common Pitfalls

  • Over-validating documents
  • Ignoring query patterns
  • Not planning for growth
  • Poor data type choices
  • Inadequate indexing

Next Steps

Now that you understand schema design, you can explore: