Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

MongoDB Query Analysis

MongoDB Query Analysis

MongoDB Query Analysis can ensure whether the indexes we have created are effective, and is an important tool for query statement performance analysis.

Commonly used functions in MongoDB Query Analysis are: explain() and hint().


Using explain()

The explain operation provides query information, index usage, query statistics, etc. It helps us optimize indexes.

Next we create indexes on gender and user_name 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 above 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 of this result set:


Using hint()

Although the MongoDB query optimizer generally works well, you can also use hint to force MongoDB to use a specified index.

This approach can improve performance in some cases: a collection with indexes and a multi-field query (some fields are indexed).

The following query example specifies using the gender and user_name index fields for the query:



>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()