4 Hours

5. Indexing & Query Performance

Performance

Making MongoDB Queries Blazingly Fast

MongoDB that works correctly but slowly will fail in production. This module covers the full stack of MongoDB performance — from understanding B-tree indexes, to reading explain() plans, to query optimization strategies — giving you the tools to diagnose and fix any slow query.

Performance is critical for any production application. MongoDB uses B-tree indexes to speed up queries. Without indexes, MongoDB scans every document in a collection (collection scan). With proper indexes, queries become fast and efficient. Understanding when and how to use indexes is essential. The explain() method shows query execution plans. It reveals which indexes are used and where the bottlenecks are. The query optimizer chooses the best plan based on index availability and statistics. This module covers index types, index creation, query optimization, and performance monitoring.

Understanding Indexes

MongoDB indexes work like book indexes. They store a small subset of data in a sorted structure. This allows the database to find documents quickly without scanning the entire collection. Indexes support equality matches, range queries, and sorting. The B-tree index is the default. It supports all types of queries. Compound indexes index multiple fields. Multikey indexes index array fields. Text indexes support full-text search. Geospatial indexes support location-based queries. Hashed indexes support sharding. Understanding index types is essential for query optimization. Choose the right index for your query patterns.

JavaScript
// Create a single-field index
await collection.createIndex({ name: 1 });

// Create a compound index
await collection.createIndex({ age: 1, name: 1 });

// Create a unique index
await collection.createIndex({ email: 1 }, { unique: true });

// Create a text index
await collection.createIndex({ description: 'text' });

// Create a geospatial index
await collection.createIndex({ location: '2dsphere' });

// Create a hashed index
await collection.createIndex({ userId: 'hashed' });

// Create an index with a name
await collection.createIndex({ name: 1 }, { name: 'name_idx' });

// List indexes
const indexes = await collection.indexes();
console.log(indexes);

// Drop an index
await collection.dropIndex('name_idx');

Reading explain() Plans

The explain() method shows how MongoDB executes a query. It reveals the query plan, index usage, and performance statistics. explain(executionStats) provides detailed execution statistics, including the number of documents scanned and the execution time. The winningPlan shows the chosen execution plan. Look for IXSCAN (index scan) vs COLLSCAN (collection scan). IXSCAN is good — the query used an index. COLLSCAN is bad — the query scanned every document. The totalDocsExamined should be close to the total number of documents returned. Understanding explain() is essential for query optimization.

JavaScript
// Basic explain
const plan = await collection.find({ age: { $gt: 30 } }).explain();
console.log(plan);

// Explain with execution stats
const stats = await collection.find({ age: { $gt: 30 } }).explain('executionStats');
console.log('Total docs examined:', stats.executionStats.totalDocsExamined);
console.log('Index used:', stats.queryPlanner.winningPlan.inputStage.indexName);

// Explain with all query execution stats
const allStats = await collection.find({ age: { $gt: 30 } }).explain('allPlansExecution');
console.log(allStats);

Query Optimization Strategies

Query optimization is the process of improving query performance. Use indexes to support your most common queries. Write selective queries that use indexes. Use projection to return only the fields you need. Use pagination with limit and skip. Use covered queries when the index contains all the data needed. Use the query optimizer hints to force a specific index. Monitor slow queries with the database profiler. Query optimization is an ongoing process. Regularly review and optimize your queries.

  • Use Indexes: Create indexes for your most common queries.
  • Selective Queries: Write queries that use indexes effectively.
  • Projection: Return only the fields you need.
  • Pagination: Use limit and skip for large result sets.
  • Covered Queries: Use indexes that contain all the data needed.
  • Database Profiler: Monitor and analyze slow queries.

Knowledge Check

Ready to test your understanding of 5. Indexing & Query Performance?

Back