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) 

Back to MongoDB โ€” Documents & data modeling

Browse all study material on Careeroza