[MongoDB Learning Note 24] explain and hint functions of MongoDB
1. explain function
The explain function can provide a lot of information about queries, and if it's a slow query, it's the most important diagnostic tool. For example:
Query on indexed fields:
> db.post.find({"loc.city":"ny"}).explain() { "cursor" : "BtreeCursor loc.city_1", "isMultiKey" : false, "n" : 0, "nscannedObjects" : 0, "nscanned" : 0, "nscannedObjectsAllPlans" : 0, "nscannedAllPlans" : 0, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 0, "nChunkSkips" : 0, "millis" : 1, "indexBounds" : { "loc.city" : [ [ "ny", "ny" ] ] }, "server" : "localhost.localdomain:27017", "filterSet" : false } >
Query on fields without indexes:
> db.post.find({"name":"joe"}).explain() { "cursor" : "BasicCursor", "isMultiKey" : false, "n" : 2, "nscannedObjects" : 15, "nscanned" : 15, "nscannedObjectsAllPlans" : 15, "nscannedAllPlans" : 15, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 0, "nChunkSkips" : 0, "millis" : 0, "server" : "localhost.localdomain:27017", "filterSet" : false } >
Compare the two queries above, and explain the fields in the explain result:
"cursor":"BasicCursor" indicates that no index is used in this query;"BtreeCursor loc.city" indicates that the index on loc.city is used;
"isMultikey" indicates whether multikey indexing is used;
"n": Number of documents returned by this query;
"nscannedObjects": indicates the number of times the actual document is actually found on disk according to the index pointer;
"nscanned": if there is no index, this number is the number of index entries searched;
"scanAndOrder": whether the result set is sorted;
"indexOnly": whether the index can be completed by using the index;
"nYields": the query pauses if there is a write operation in the middle of the query; this field represents the number of times the query pauses due to write operations;
" millis": the number of times spent on this query, the smaller the number, the higher the query efficiency;
"indexBounds": This field describes the usage of the index and gives the range of index traversal.
"filterSet" : whether to use and index filtering;
2. Hint function
If you find that the index used by MongoDB is inconsistent with your desired index, You can use the hit function to force MongoDB to use a specific index. for example
>db.users.find({"age":1,"username":/.*/}). hint({"username":1,"age":1})