Understanding MongoDB Query Plan

MongoDBDatabaseBig Data Analytics

To get a query plan in MongoDB, use explain(). The $explain operator gives information on the query plan.

Let us create a collection with documents −

> db.demo408.insertOne({"Value":50});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e70e3a115dc524f70227678")
}
> db.demo408.insertOne({"Value":20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e70e3a715dc524f70227679")
}
> db.demo408.insertOne({"Value":45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e70e3ac15dc524f7022767a")
}
> db.demo408.insertOne({"Value":35});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e70e3af15dc524f7022767b")
}
> db.demo408.createIndex({Value:1});
{
   "createdCollectionAutomatically" : false,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}

Display all documents from a collection with the help of find() method −

> db.demo408.find();

This will produce the following output −

{ "_id" : ObjectId("5e70e3a115dc524f70227678"), "Value" : 50 }
{ "_id" : ObjectId("5e70e3a715dc524f70227679"), "Value" : 20 }
{ "_id" : ObjectId("5e70e3ac15dc524f7022767a"), "Value" : 45 }
{ "_id" : ObjectId("5e70e3af15dc524f7022767b"), "Value" : 35 }

Following is the query to understand query plan in MongoDB −

> db.demo408.explain().find( { Value: { $gt: 40 } } );

This will produce the following output −

{
   "queryPlanner" : {
      "plannerVersion" : 1,
      "namespace" : "test.demo408",
      "indexFilterSet" : false,
      "parsedQuery" : {
         "Value" : {
            "$gt" : 40
         }
      },
      "winningPlan" : {
         "stage" : "FETCH",
         "inputStage" : {
            "stage" : "IXSCAN",
            "keyPattern" : {
               "Value" : 1
            },
            "indexName" : "Value_1",
            "isMultiKey" : false,
            "multiKeyPaths" : {
               "Value" : [ ]
            },
            "isUnique" : false,
            "isSparse" : false,
            "isPartial" : false,
            "indexVersion" : 2,
            "direction" : "forward",
            "indexBounds" : {
               "Value" : [
                  "(40.0, inf.0]"
               ]
            }
         }
      },
      "rejectedPlans" : [ ]
   },
   "serverInfo" : {
      "host" : "DESKTOP-QN2RB3H",
      "port" : 27017,
      "version" : "4.0.5",
      "gitVersion" : "3739429dd92b92d1b0ab120911a23d50bf03c412"
   },
   "ok" : 1
}
raja
Updated on 03-Apr-2020 13:13:53

Advertisements