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:

//these also worked in version 2.2:

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

Variables in Mongo query

If you ever want to create dynamic queries that you will then pass to a Mongo command, here’s how to do it:

var query = {};
query['key'] = value; 

// check a condition		    
   query['key1'] = true;

    if(error) callback(error);