Latest web development tutorials

MongoDB query analysis

MongoDB query and analysis to ensure the effectiveness of our proposed index is an important tool to query performance analysis.

MongoDB query analysis commonly used functions are: explain () and hint ().

Use explain ()

explain operation provides query information, use the index and query statistics. Help us to optimize the index.

Next we create an index gender and user_name users in the collection:

<p>现在在查询语句中使用 explain :</p>

Above explain () query returns the following results:

   "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" : [
      "user_name" : [
               "$minElement" : 1
               "$maxElement" : 1

Now, we look at the field of the result set:

  • indexOnly: field is true, that we use the index.
  • cursor: Because this query uses the index, MongoDB indexes are stored in B-tree structure, so it is also used BtreeCursor type of cursor. If you do not use the index, the cursor type is BasicCursor. This key will give the name of the index you are using, you can see by the name system.indexes set under the current database (created automatically, since the index information is stored, this will be mentioned a little) to get more information Index .
  • n: number of documents returned by the current query.
  • nscanned / nscannedObjects: The inquiry showed that the current total number of scanned documents in the collection, our aim is to make this value and returns the number of documents the closer the better.
  • millis: the current time, the number of milliseconds needed by the query.
  • indexBounds: the current query index specific use.

Use hint ()

While MongoDB query optimizer generally work very well, but you can also use hints to force MongoDB to use a specified index.

This approach will improve performance in some cases. An index of the collection and execute the query more than one field (some fields have been indexed).

Examples use the following query specifies the gender and user_name index fields to the query:


You can use the explain () function to parse the above query: