Introduction
Indexes help MongoDB find data faster. Identifying missing indexes shows where queries can be improved to run quicker.
db.collection.getIndexes()
db.collection.find().explain('queryPlanner')
use system.profile collection to check slow queriesdb.collection.getIndexes() to see existing indexes on a collection.explain() on queries to see if indexes are used or missing.db.orders.getIndexes()
db.orders.find({customerId: 123}).explain('executionStats')db.system.profile.find({millis: {$gt: 100}}).sort({ts: -1}).limit(5)use shopDB // Check existing indexes on products collection printjson(db.products.getIndexes()) // Run a query and explain to see if index is used var explainResult = db.products.find({category: 'books'}).explain('executionStats') printjson(explainResult.queryPlanner) // Check slow queries from profiler var slowQueries = db.system.profile.find({millis: {$gt: 50}}).sort({ts: -1}).limit(3).toArray() printjson(slowQueries)
COLLSCAN (collection scan), it means no index was used and performance can be slow.system.profile collection stores recent slow queries if profiling is enabled.getIndexes() and explain() to check if indexes exist and are used.system.profile to find where indexes are missing.users?listIndexes().db.users.listIndexes() is a valid MongoDB command; others are incorrect or do not exist.db.orders.find({ customerId: 123 }) and the collection has no index on customerId, what will explain('executionStats') likely show?customerId, MongoDB must scan the entire collection (COLLSCAN) to find matching documents.explain('executionStats') will show a COLLSCAN and a high number of documents examined, indicating no index was used.db.products.find({ category: 'books', price: { $lt: 20 } }). The collection has an index only on category. What is the best fix?category and price, but only category is indexed, so the price filter is not optimized.{ category: 1, price: 1 } allows MongoDB to efficiently filter by both fields, speeding up the query.logs has slow queries filtering by userId and sorting by timestamp. Which index best improves performance?userId and sorts by timestamp, so both fields affect performance.{ userId: 1, timestamp: -1 } supports efficient filtering by userId and sorting by timestamp in descending order.Pass the test and this pattern moves unknown