Patterns

Different Types of patterns

What is Schema Design in MongoDB?

Schema design means how you structure your data (documents & collections).


Since MongoDB is flexible, good design is very important for performance and scalability


🔹 Key Idea

In MongoDB, you mainly decide between:

  • Embedding (store together)
  • Referencing (store separately and link)


🔹 1. Embedded Pattern (Denormalization)


Store related data inside one document

Example:

User document contains address inside it


Advantages

  • Fast reads (no joins needed)
  • Simple queries

Disadvantages

  • Data duplication
  • Large document size

Use When

  • Data is frequently read together
  • One-to-few relationship


🔹 2. Referenced Pattern (Normalization)

Store data in separate collections and link using IDs


Example:

  • users collection
  • orders collection (with userId)


Advantages

  • No duplication
  • Better for large or complex data


Disadvantages

  • Needs joins ($lookup)
  • Slightly slower


Use When

  • One-to-many or many-to-many relationships
  • Data is large or frequently updated


🔹 3. Bucket Pattern


Group similar data into one document

Example:

Store multiple time-series records in one document


Use Cases

  • IoT data
  • Logs
  • Time-based data


🔹 4. Computed Pattern


Store pre-calculated values

Example:

Store totalOrderAmount in user document


Advantage

  • Faster reads


Disadvantage

  • Needs updates when data changes


🔹 5. Subset Pattern

Store only important data in main document, rest separately


Example:

User document → basic info
Another collection → detailed logs


Use Case

  • Improve performance by reducing document size


🔹 6. Extended Reference Pattern

Combine embedding + referencing

  • Store some fields embedded
  • Keep full data in another collection


Example:

Order document stores:

  • product name (embedded)
  • productId (reference)


🔹 7. Polymorphic Pattern

Store different types of documents in same collection

Example:

Payments collection:

  • card payment
  • UPI payment
  • net banking


Simple Understanding

  • Embed → fast reads
  • Reference → flexible & scalable
  • Other patterns → optimize specific use cases