MongoDB Query Analysis
MongoDB query analysis ensures the effectiveness of the indexes we create and is an essential tool for analyzing query performance.
Common functions used in MongoDB query analysis include: explain()
and hint()
.
Using explain()
The explain
operation provides information about the query, the indexes used, and query statistics. This is beneficial for optimizing our indexes.
Next, we will create an index on the gender
and user_name
fields in the users
collection:
>db.users.ensureIndex({gender:1, user_name:1})
Now, use explain
in the query statement:
>db.users.find({gender:"M"}, {user_name:1, _id:0}).explain()
The explain()
query returns the following result:
{
"cursor" : "BtreeCursor gender_1_user_name_1",
"isMultiKey" : false,
"n" : 1,
"nscannedObjects" : 0,
"nscanned" : 1,
"nscannedObjectsAllPlans" : 0,
"nscannedAllPlans" : 1,
"scanAndOrder" : false,
"indexOnly" : true,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
"indexBounds" : {
"gender" : [
[
"M",
"M"
]
],
"user_name" : [
[
{
"$minElement" : 1
},
{
"$maxElement" : 1
}
]
]
}
}
Now, let's look at the fields in this result set:
indexOnly: If this field is
true
, it indicates that we used the index.cursor: Since this query used an index, MongoDB stores indexes in a B-tree structure, so a cursor of type
BtreeCursor
is used. If no index is used, the cursor type isBasicCursor
. This key also provides the name of the index used, which can be used to view detailed information about the index in thesystem.indexes
collection (automatically created to store index information).n: The number of documents returned by the current query.
nscanned/nscannedObjects: Indicates how many documents were scanned in the collection for this query. Ideally, this number should be close to the number of documents returned.
millis: The time taken for the current query in milliseconds.
indexBounds: The specific index used by the current query.
Using hint()
Although MongoDB's query optimizer generally works well, you can use hint
to force MongoDB to use a specified index.
This method can improve performance in certain situations, such as when querying a collection with indexed fields.
The following query example specifies the use of the gender
and user_name
index fields:
>db.users.find({gender:"M"}, {user_name:1, _id:0}).hint({gender:1, user_name:1})
You can use the explain()
function to analyze the above query:
>db.users.find({gender:"M"}, {user_name:1, _id:0}).hint({gender:1, user_name:1}).explain()