要在MongoDB中获取查询计划,请使用explain()
。$explain运算符提供有关查询计划的信息。
让我们创建一个包含文档的集合-
> 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 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo408.find();
这将产生以下输出-
{ "_id" : ObjectId("5e70e3a115dc524f70227678"), "Value" : 50 } { "_id" : ObjectId("5e70e3a715dc524f70227679"), "Value" : 20 } { "_id" : ObjectId("5e70e3ac15dc524f7022767a"), "Value" : 45 } { "_id" : ObjectId("5e70e3af15dc524f7022767b"), "Value" : 35 }
以下是查询以了解MongoDB中的查询计划-
> db.demo408.explain().find( { Value: { $gt: 40 } } );
这将产生以下输出-
{ "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 }