2

I'm new to Mongo and have searched but don't see a specific answer.

I understand that Mongo explain method will execute the query in parallel with possible access plans and choose a winning plan based on execution time.

The Best Practices Guide states "The query plan can be calculated and returned without first having to run the query". I cannot find how to do this in the doc.

So what if even the winning plan takes a very long time to execute before it returns even a small result set, for example sorting a large collection?

I've seen older comments that execution stops after the first 101 documents are returned, but again can't find that in official doc.

So my question is: How to get the access plan without executing the query?

Thanks for your help. I'm using Mongo 3.4.

Fabien
  • 4,862
  • 2
  • 19
  • 33

2 Answers2

1

You can set the verbosity of the explain() function. By default it uses the queryPlanner which is (if I'm right) what you are looking for.

Check the other modes in the official MongoDB documentation about explain()

mgyongyosi
  • 2,557
  • 2
  • 13
  • 20
  • Thanks. I read the queryPlanner doc but wasn't clear on it because it states that it doesn't return execution results, but that doesn't explicitly mean that the query wasn't executed, just that results aren't returned. I believe you are correct tho. – Jim Fletcher Jul 30 '17 at 22:36
0

MongoDB builds Query Plans by running a limited subset of a query, then caches the winning plan so it can be re-used (until something causes a cache flush).

So the "limited subset" means that it will get documents that match up to the 100 docs as a "sample", and go no further, but what the documentation means by

The query plan can be calculated and returned without first having to run the query

is that you can do an explain before you run the full query. This is good practice because it then populates that Plan Cache for you ahead of time.

To put it simply, if MongoDB notices that another query is taking longer than a completed query, it will cease execution and ditch the plan in favour of the more efficient plan. For example, you can see this in action by running the allPlansExecution explain where an index is chosen over a colscan.