Database Reference
In-Depth Information
But before moving on, a few more words about profiling strategy are in order. A
good way to use the profiler is to start it with a coarse setting and work downward. First
ensure that no queries take longer than 100 ms, then move down to 75 ms, and so on.
While the profiler is enabled, you'll want to put your application through its paces. At
a minimum, this means ensuring that every read and write is performed. But to be
thorough, those reads and writes must be executed under real conditions, where the
data sizes, query load, and hardware are representative of the application's produc-
tion environment.
The query profiler is useful, but to get the most out of it, you need to be methodi-
cal. Better to be surprised with a few slow queries in development than in production,
where the remedies are much more costly.
7.3.2
Examining slow queries
With MongoDB's profiler, finding slow queries is easy. Discovering why these queries
are slow is trickier because the process may require some detective work. As men-
tioned, the causes of slow queries are manifold. If you're lucky, then resolving a slow
query may be as easy as adding an index. In more difficult cases, you might have to
rearrange indexes, restructure the data model, or upgrade hardware. But you should
always look at the simplest case first, and that's what you're going to do here.
In the simplest case, a lack of indexes, inappropriate indexes, or less-than-ideal
queries will be the root of the problem. You can find out for sure by running an
explain on the offending queries. Let's explore how to do that now.
U SING AND UNDERSTANDING EXPLAIN ()
MongoDB's explain command provides detailed information about a given query's
path. 11 Let's dive right in and see what information can be gleaned from running an
explain on the last query you ran in the previous section. To run explain from the
shell, you need only attach the explain() method call:
db.values.find({}).sort({close: -1}).limit(1).explain()
{
"cursor" : "BasicCursor",
"nscanned" : 4308303,
"nscannedObjects" : 4308303,
"n" : 1,
"scanAndOrder" : true,
"millis" : 14576,
"nYields" : 0,
"nChunkSkips" : 0,
"indexBounds" : { }
}
The millis field indicates that this query takes more than 14 seconds, and there's
an obvious reason for this. Look at the nscanned value: this shows that the query
11
You may recall that I introduced explain in chapter 2, but only briefly. Here I'll provide a complete treat-
ment of the command and its output.
Search WWH ::




Custom Search