#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
7 min read
Question 27 of 27hard

What are common MongoDB data modeling patterns?

Advanced schema design patterns.

What You'll Learn

  • Common patterns
  • When to use each
  • Implementation examples

1. Subset Pattern

Store frequently accessed subset in main document.

code.jsJavaScript
// Product with recent reviews embedded
{
  _id: 1,
  name: "Laptop",
  price: 999,
  recentReviews: [
    { user: "Alice", rating: 5, text: "Great!" },
    { user: "Bob", rating: 4, text: "Good value" }
  ],
  totalReviews: 1500
}
// All reviews in separate collection

2. Computed Pattern

Pre-compute frequently needed values.

code.jsJavaScript
{
  _id: 1,
  title: "Blog Post",
  views: 15234,
  likes: 892,
  // Pre-computed
  engagement: 0.058,  // likes/views
  isPopular: true     // views > 10000
}

3. Bucket Pattern

Group related data into buckets.

code.jsJavaScript
// Instead of one doc per reading
{
  sensorId: "temp-1",
  date: "2024-01-15",
  readings: [
    { time: "00:00", value: 22.5 },
    { time: "00:05", value: 22.6 },
    // ... more readings
  ],
  count: 288,
  avg: 22.8,
  min: 20.1,
  max: 25.3
}

4. Extended Reference Pattern

Embed frequently accessed fields from related documents.

code.jsJavaScript
// Order with embedded user info
{
  _id: 1,
  userId: ObjectId("..."),
  // Extended reference - copied fields
  userName: "John Doe",
  userEmail: "john@example.com",
  items: [...],
  total: 299.99
}

5. Polymorphic Pattern

Store different types in same collection.

code.jsJavaScript
// Products collection with different types
{ type: "book", title: "MongoDB Guide", author: "..." }
{ type: "electronics", name: "Laptop", specs: {...} }
{ type: "clothing", name: "T-Shirt", size: "M" }

6. Attribute Pattern

Handle varied attributes efficiently.

code.jsJavaScript
// Instead of sparse fields
{
  name: "Product",
  attributes: [
    { k: "color", v: "red" },
    { k: "size", v: "large" },
    { k: "material", v: "cotton" }
  ]
}
// Can index: { "attributes.k": 1, "attributes.v": 1 }