Indexes, Query Plans, and Data Access Patterns

An index is an additional data structure that helps the database locate records without scanning every row or document. It speeds selected reads but consumes storage and adds work to writes and updates. The correct index depends on filter predicates, sort order, cardinality, and query shape.

For a query filtering by status and sorting by createdAt, a compound index such as { status: 1, createdAt: -1 } may help. Field order matters: an index is not a universal accelerator for every query. Inspect execution plans and examine examined-versus-returned records, sort stages, and index usage.

Avoid creating indexes based on guesses alone. Use representative production-like data, observe slow queries, and test changes against realistic distributions. Indexes can become ineffective when predicates are not selective or when the query requests a large fraction of the collection.

MongoDB compound index
db.orders.createIndex({ status: 1, createdAt: -1 });
db.orders.find({ status: "PAID" })
  .sort({ createdAt: -1 })
  .limit(50)
  .explain("executionStats");
💡 The compound index may support filtering by status and ordering by creation time. Confirm the actual winning plan with representative data; index choice depends on selectivity and the full query.
Key Takeaways
  • Indexes trade write cost and storage for faster access paths.
  • Compound index field order is important.
  • Use execution plans rather than assuming an index is being used.