0
0
MongoDBquery~5 mins

Index usage verification in MongoDB

Choose your learning style9 modes available
Introduction

Indexes help MongoDB find data faster. Checking index usage shows if queries use these indexes well.

You want to speed up a slow search in your database.
You added an index and want to see if queries use it.
You want to find queries that do not use indexes and might be slow.
You are optimizing your database for better performance.
Syntax
MongoDB
db.collection.find(query).explain('executionStats')

This command shows how MongoDB runs your query.

Look for indexName and totalKeysExamined in the output to see index usage.

Examples
Check if the query searching users by age uses an index.
MongoDB
db.users.find({ age: 25 }).explain('executionStats')
Verify if the orders query uses an index on the status field.
MongoDB
db.orders.find({ status: 'shipped' }).explain('executionStats')
Sample Program

First, create an index on the category field. Then, run a query to find products in the 'books' category and check if the index is used.

MongoDB
db.products.createIndex({ category: 1 })
db.products.find({ category: 'books' }).explain('executionStats')
OutputSuccess
Important Notes

Use explain('executionStats') to get detailed info about index use.

If stage is COLLSCAN, the query did not use an index and scanned all documents.

Indexes speed up queries but take space and slow writes, so check usage carefully.

Summary

Indexes make queries faster by helping MongoDB find data quickly.

Use explain('executionStats') to see if a query uses an index.

Look for IXSCAN stage and indexName in the explain output to confirm index usage.