- MongoDB CRUD Operations >
- MongoDB CRUD Tutorials >
- Analyze Query Performance
Analyze Query Performance¶
The explain()
cursor method allows you to inspect the
operation of the query system. This method is useful for analyzing the
efficiency of queries, and for determining how the query uses the
index. The explain()
method tests the query
operation, and not the timing of query performance. Because
explain()
attempts multiple query plans, it does not
reflect an accurate timing of query performance.
Evaluate the Performance of a Query¶
To use the explain()
method, call the method on a
cursor returned by find()
.
Example
Evaluate a query on the type
field on the collection
inventory
that has an index on the type
field.
Consider the results:
The BtreeCursor
value of the cursor
field
indicates that the query used an index.
This query returned 5 documents, as indicated by the
n
field.
To return these 5 documents, the query scanned 5 documents from the
index, as indicated by the nscanned
field, and then
read 5 full documents from the collection, as indicated by the
nscannedObjects
field.
Without the index, the query would have scanned the whole collection to return the 5 documents.
See Explain Results method for full details on the output.
Compare Performance of Indexes¶
To manually compare the performance of a query using more than one
index, you can use the hint()
and
explain()
methods in conjunction.
Example
Evaluate a query using different indexes:
These return the statistics regarding the execution of the query using the respective index.
Note
If you run explain()
without including
hint()
, the query optimizer reevaluates
the query and runs against multiple indexes before returning the
query statistics.
For more detail on the explain output, see Explain Results.