Explain plans & performance in MongoDB
medium ยท MongoDB โ Documents & data modeling
๐น 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)