← Back to MongoDB Course | Chapter 8: Indexes | Lesson 6 of 7

explain()

explain shows how MongoDB executes a query: which index it used and how many documents it examined.

In this page:

  1. explain()
Syntax
javascript
db.collection_name.find(filter).explain("executionStats")

explain()

Call .explain("executionStats") on a cursor. Look at winningPlan for IXSCAN (index scan) versus COLLSCAN (full scan), and compare totalDocsExamined with nReturned.

A large gap means the query is inefficient. hint() forces a particular index for testing.

Note: Aim for totalDocsExamined close to nReturned.

Example: explain()

bash
test> db.users.find({ email: "[email protected]" }).explain("executionStats").executionStats
{
  nReturned: 1,
  totalKeysExamined: 1,
  totalDocsExamined: 1,
  executionStages: { stage: 'FETCH', inputStage: { stage: 'IXSCAN', indexName: 'email_1' } }
}

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Ignoring COLLSCAN in plans
  2. Trusting timing on tiny data
  3. Not comparing docs examined with returned
Chapter Summary
  • explain shows the query plan
  • IXSCAN uses an index, COLLSCAN does not
  • Compare docs examined and returned
  • hint forces an index
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.