Performance Tools and Techniques / Tools for Optimizing Indexes
Code Recap: Tools for Optimizing Indexes
Below is the code used to run the explain()
method in mongosh
to return an explain plan. An explain plan is a report that gives us information about possible plans for executing a query, including the winning plan that MongoDB selects.
Code
explain()
Method
Use the explain()
method, chained with the find()
method to return the explain plan in mongosh
.
db.collection.explain().find()
Example Query
This query is used to retrieve documents from the listingsAndReviews_big_collection
collection for all documents that match on property_type
and room_type
that allow a specific range of nights to stay with at least 2 bedrooms
. The results are then sorted by the number_of_reviews
in descending order.
The explain()
method is chained to this query with verbosity level set to executionStats
. This will return an explain plan document in the terminal that will include execution stats for the winning plan.
db.listingsAndReviews_big_collection
.explain("executionStats")
.find(
{ property_type: 'House', room_type: 'Entire home/apt', minimum_nights: { $gt: '2' }
,
maximum_nights: { $lte: '30' }, bedrooms: { $gte: 2 }
})
.sort({ number_of_reviews: -1 })
Handling Indexes
Below are the code snippets used to work with Indexes in mongosh
.
Use the createIndex
database command to create an index on a collection with different properties.
This command creates an index on the email
field only and stores the values in ascending order.
db.users.createIndex({ email: 1 })
This command creates an index on the email
and the status
fields and stores the values in ascending order.
db.users.createIndex({ email: 1, status: 1})
The getIndexes()
command retrieves the indexes that exist on a specific collection.
db.users.getIndexes()
The hideIndex()
command disables the email_1
index temporarily. The query planner ignores the index during execution, but it remains stored in the metadata and can be re-enabled later.
db.users.hideIndex("email_1")
The dropIndex()
command permanently removes the email_1
index, reducing storage and maintenance overhead. Dropping unused indexes can optimize storage and enhance performance when irrelevant indexes are eliminated.
db.users.dropIndex("email_1")