explain

Plans and Perfomance

🔹 What are Query Plans?


When you run a query, MongoDB has multiple ways (plans) to execute it.

A query plan is the strategy MongoDB chooses to:

  • find data
  • use indexes (or not)
  • return results efficiently


🔹 How MongoDB Chooses a Plan

MongoDB’s query optimizer:

  • checks available indexes
  • tries different execution plans
  • picks the fastest one

This is automatic — you don’t manually choose (in most cases)


🔹 Check Query Plan

You can see how a query runs using:

db.users.find({ age: 25 }).explain("executionStats")

It shows:

  • which index is used
  • number of documents scanned
  • execution time


🔹 Important Terms

1. COLLSCAN (Collection Scan)

MongoDB scans entire collection

  • Slow 
  • Happens when no index is used


2. IXSCAN (Index Scan)

MongoDB uses an index

  • Fast 
  • Best case


3. Execution Stats

Shows:

  • documents examined
  • documents returned
  • time taken

Helps measure performance


🔹 Covered Query

A query that is fully satisfied by an index

  • No need to read actual documents
  • Very fast 

Example idea:
If index has (name, age), and query asks only those → covered


🔹 Query Performance Tips

Use Indexes Properly

  • Index fields used in queries
  • Especially for filtering & sorting


Avoid Full Collection Scans

  • Always try to avoid COLLSCAN


Limit Data

  • Use limit() to reduce results


Use Projection

  • Fetch only required fields


Use Compound Index Wisely

  • Order of fields matters


🔹 Index Selection Example

If you have index on:
age


Query:

db.users.find({ age: 25 })

MongoDB uses IXSCAN → fast


Without index:
COLLSCAN → slow


🔥 Simple Understanding

  • Query Plan = how MongoDB executes a query
  • IXSCAN = fast (uses index)
  • COLLSCAN = slow (no index)