21. Index Design and Schema Design Together

Index design depends on the data model. If an application frequently queries a relationship, decide whether the relationship should be embedded or referenced, and which access patterns must be fast.

Embedding can make common reads efficient without $lookup, but arrays can grow and multikey indexes may become large. References can reduce duplication and support independent updates, but joins may add cost.

For each important query, document its filter, sort, projection, expected result size, frequency, and latency target. Then propose indexes and test them. Avoid indexing every field in a schema simply because it might be queried someday.

Index design should be revisited when product behavior changes. A new dashboard or API endpoint can introduce a query pattern that was not part of the original workload.

Code Example
db.orders.createIndex({ customerId: 1, createdAt: -1 });

db.orders.find({ customerId: 501 })
  .sort({ createdAt: -1 })
  .limit(20);
Key Takeaways
  • Index design and schema design influence each other.
  • Model around actual access patterns.
  • Document filters, sorts, projections, and expected result sizes.
  • Revisit indexes when application workloads change.
Knowledge Check

What is a strong starting point for index design?