How to Optimize MongoDB Query Performance with Indexes

· databases · Source ↗

TLDR

  • Workflow for fixing slow MongoDB queries: profile with explain(), get compound index recommendations, and manage indexes visually in VisuaLeaf.

Key Takeaways

  • Use explain("executionStats") to check totalDocsExamined vs nReturned; a 50,000:25 ratio signals a missing index.
  • Follow the ESR rule for compound indexes: equality fields first (currency, status), sort second (paidAt), range last (amount).
  • db.payments.createIndex({ currency: 1, status: 1, paidAt: -1, amount: 1 }) covers filter, sort, and range in one index.
  • Over-indexing has real costs: each index adds storage and write overhead on every insert, update, and delete.
  • VisuaLeaf’s Index Manager surfaces unused and redundant indexes, helping prune stale indexes as query patterns change.

Hacker News Comment Review

  • No substantive HN discussion yet.

Original | Discuss on HN