I Demand An Explanation — MongoDB Edition
Identifying potential performance bottlenecks in your MongoDB queries can be tricky, even challenging.
To help developers better understand what happens under the hood, MongoDB provides the explain method.
In this article, we’re going to explore what information the explain method provides.
Note: I’ll be using a Rubygem I wrote to augment MongoDB’s explain output. Throughout this article, I’m going to assume that you’ve installed this gem.
Note: I’ll be using a Rubygem I wrote to augment MongoDB’s explain output. Throughout this article, I’m going to assume that you’ve installed this gem.
You can install the gem by following this link.
Terminologies
Winning Plan
The plan that was chosen by MongoDB’s query optimizer for execution. One or more other plans might be considered before executing the winning plan.
Rejected Plans
Plans tested partially by the query optimizer but were rejected in favor of another plan, i.e. the winning plan.
Documents Examined
Documents scanned by MongoDB during query execution.
Documents Returned
Documents returned by MongoDB during query execution.
Keys Examined
Indexes scanned by MongoDB during query execution.
Show me the code
Let’s dive directly into a few queries examples and start explaining the queries. Consider the following; we have a Rails app that includes the following models:
- Article — Represents a blog post or article.
- Author — The author of one or more blog posts.
The following would be a typical representation of this relation using Mongoid.
Now let’s fetch all articles for a specific author and examine the explain output.
Depending on the number of articles and authors you have (or any other model(s) you’re testing) you will get an output similar to the following:
We can see in the above table that
- This query used the
author_id_1
index 7
documents were examined1
index/key was examined7
documents were returned0
rejected plans, which is good. This means the query optimizer didn’t have to waste time partially testing other plans.0
rejected plans, which is good. This means the query optimizer didn’t have to spend unneeded extra time partially testing other plans.