MongoDB query analysis ensures that our proposed indexes are valid and is an important tool for performance analysis of query statements.
MongoDB query analysis commonly used functions are: explain () and hint ().
Using Explain ()
Explain operations provide query information, use indexes and query statistics, and so on. Facilitates our optimization of the index.
Next we create indexes for gender and user_name in the Users collection:
>db.users.ensureindex ({gender:1,user_name:1}) </p><p> now uses explain in query statements:</p><pre>> Db.users.find ({gender: "M"},{user_name:1,_id:0}). Explain ()
The explain () query above returns the following results:
{ "cursor": "Btreecursor gender_1_user_name_1", "Ismultikey": false, "n": 1, "nscannedobjects": 0,< c4/> "nscanned": 1, "Nscannedobjectsallplans": 0, "Nscannedallplans": 1, "Scanandorder": false, " IndexOnly ": True, " Nyields ": 0, " nchunkskips ": 0, " Millis ": 0, " indexbounds ": { " gender ": [ c14/>[ "M", "M" ] ], "user_name": [ [ { "$minElement": 1 }, { "$maxElement": 1 } ] }}
Now, let's look at the fields of this result set:
- indexOnly: The field is true, indicating that we used the index.
- cursor: Because this query uses an index, the index in MongoDB is stored in the B-tree structure, so this is also a cursor of type btreecursor. If the index is not used, the cursor type is basiccursor. This key will also give you the name of the index you are using, you can see the System.indexes collection under the current database (the system is automatically created, because the storage index information, this is slightly mentioned) to get the detailed information of the index.
- N: The number of documents returned by the current query.
- nscanned/nscannedobjects: Indicates how many documents in the collection are currently scanned by this query, and our goal is to get this number and return document as close as possible.
- Millis: The current time required for the query, in milliseconds.
- indexbounds: The index used by the current query.
Using Hint ()
Although the MongoDB query optimizer generally works well, you can also use hints to force MongoDB to use a specified index.
This approach improves performance in some cases. An indexed collection and executes a multi-field query (some fields are already indexed).
The following query instance specifies the query using 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 parse the above query:
>db.users.find ({gender: "M"},{user_name:1,_id:0}). Hint ({gender:1,user_name:1}). Explain ()
MongoDB Query Analysis