Analyze MongoDB Query Performance

MongoDB provides explain() to inspect how a query executes.

It can reveal:

  • Whether MongoDB uses an index.
  • Whether the query performs a collection scan.
  • How many documents were examined.
  • How many documents were returned.
  • Query execution statistics.

For example, a query filtering users by email can be inspected using execution statistics.

Analyze a MongoDB Query
const result = await User.find({
  email: 'john@example.com'
}).explain('executionStats');

console.log(result.executionStats);

Returns execution statistics for the email lookup query.

Key Takeaways
  • explain() helps diagnose query execution.

  • Inspect documents examined and returned.

  • Use query plans to identify missing indexes and inefficient queries.