4 Hours

2. Schema Design & Data Modeling

Data Modeling

Designing MongoDB Schemas the Right Way

MongoDB's flexible document model is powerful, but it requires a different approach to data modeling than relational databases. Instead of normalizing data across tables, you design schemas around your application's data access patterns. This module teaches you to design schemas that are performant, scalable, and aligned with how your application queries data.

The key to MongoDB schema design is thinking in documents. You embed related data when you need to access it together. You reference data when relationships are many-to-many or when embedding would cause duplication. Schema design decisions are critical — a bad data model creates technical debt that compounds over time. Understanding when to embed versus reference is the most important skill in MongoDB schema design. You also need to consider indexing, data growth, and query patterns. This module covers the patterns and anti-patterns of MongoDB schema design.

Embedding vs Referencing

Embedding is the most common pattern in MongoDB. You embed related data in a parent document when you need to access it together. Embedding provides better performance because you read one document instead of multiple. Embedding is ideal for one-to-one and one-to-many relationships where the child data is always accessed with the parent. Referencing is used for many-to-many relationships or when the child data is accessed independently. Referencing requires multiple queries but avoids duplication. Choose embedding for read-heavy workloads where data is accessed together. Choose referencing for write-heavy workloads or when data is accessed independently. The choice depends on your application's access patterns.

Embedding

Store related data inside a parent document. Best for one-to-one and one-to-many relationships where data is accessed together. Provides better read performance.

Referencing

Store related data in separate documents with references (ObjectIds). Best for many-to-many relationships. Avoids duplication but requires multiple queries.

JavaScript
// Embedding: User with embedded address
{
  _id: ObjectId('...'),
  name: 'Alice',
  email: 'alice@example.com',
  address: {
    street: '123 Main St',
    city: 'New York',
    state: 'NY',
    zip: '10001'
  }
}

// Embedding: User with embedded posts
{
  _id: ObjectId('...'),
  name: 'Alice',
  email: 'alice@example.com',
  posts: [
    { title: 'First Post', content: 'Hello', createdAt: ISODate('2024-01-01') },
    { title: 'Second Post', content: 'Hi again', createdAt: ISODate('2024-01-02') }
  ]
}

// Referencing: User and Posts as separate collections
// users collection
{
  _id: ObjectId('user123'),
  name: 'Alice',
  email: 'alice@example.com'
}

// posts collection
{
  _id: ObjectId('post456'),
  userId: ObjectId('user123'),
  title: 'First Post',
  content: 'Hello',
  createdAt: ISODate('2024-01-01')
}

Primary Keys and _id Field

Every MongoDB document has an _id field that serves as the primary key. The _id field is automatically indexed and must be unique. By default, MongoDB generates ObjectIds, which are 12-byte identifiers that include a timestamp, machine identifier, process ID, and counter. You can also use custom values for _id, such as UUIDs or application-specific identifiers. Choosing the right _id strategy is important for performance and distribution. ObjectIds are efficient for sorting by creation time. UUIDs are better for distributed systems where you need globally unique identifiers. Application-specific IDs are useful when your data has natural keys.

JavaScript
// Default ObjectId
{
  _id: ObjectId('507f1f77bcf86cd799439011'),
  name: 'Alice'
}

// Custom _id (UUID)
{
  _id: UUID('a1b2c3d4-e5f6-7890-abcd-ef1234567890'),
  name: 'Alice'
}

// Custom _id (natural key)
{
  _id: 'alice@example.com',
  name: 'Alice'
}

// Custom _id (compound)
{
  _id: { userId: 'alice', postId: 'post123' },
  title: 'Hello',
  content: 'World'
}

Schema Design Patterns

Several patterns are widely used in MongoDB schema design. The attribute pattern stores key-value pairs for dynamic attributes. The bucket pattern groups time-series data by time interval. The computed pattern stores derived data to avoid recomputation. The extensible pattern uses arrays for evolving schemas. The subset pattern separates frequently accessed data from rarely accessed data. These patterns help you design efficient schemas for specific use cases. The attribute pattern is common for products with varying attributes. The bucket pattern is ideal for IoT and time-series data. Choose patterns based on your application's requirements.

  • Attribute Pattern: Store dynamic attributes as key-value pairs.
  • Bucket Pattern: Group time-series data by time interval.
  • Computed Pattern: Store pre-computed values for faster queries.
  • Extensible Pattern: Use arrays for evolving schemas.
  • Subset Pattern: Separate frequently accessed data from less accessed data.

Knowledge Check

Ready to test your understanding of 2. Schema Design & Data Modeling?

Back