MongoDB explain command to show all execution plans

So the MongoDB courses are almost finished, and now both MongoDB for Developers and MongoDB for DBAs tracks are in the finals phase.

One of the questions is about indexes, where you’re given the list of indexes that exists for a collection, and an example of a query. The question is to identify which indexes could potentially be used for optimization for that query.

I had my ideas for the answer, but to be sure I wanted to create a sample collection, add indexes and view all execution plans. It is in fact doable, if you pass a parameter to the “explain()” command:

db.mycoll.find({your_query_params}).explain(1)
//these also worked in version 2.2:
db.mycoll.find({your_query_params}).explain(true)
db.mycoll.find({your_query_params}).explain({$all:1})

The output will include a field called “allPlans”, which is an array of all possible combinations of indexes that could be used. Neat.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s