MongoDB - 解读 db.collection.find() 方法的查询计划信息
对于查询计划信息,在 MongoDB 中使用 explain()。让我们创建一个带有文档的集合 −
> db.demo637.ensureIndex({ClientName:1}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo637.insert({ClientName:"John"}); WriteResult({ "nInserted" : 1 }) > db.demo637.insert({ClientName:"Bob"}); WriteResult({ "nInserted" : 1 }) > db.demo637.insert({ClientName:"Johnson"}); WriteResult({ "nInserted" : 1 })
在集合中通过 find() 方法显示所有文档 −
> db.demo637.find();
将产生以下输出 −
{ "_id" : ObjectId("5e9c26916c954c74be91e6db"), "ClientName" : "John" } { "_id" : ObjectId("5e9c26936c954c74be91e6dc"), "ClientName" : "Bob" } { "_id" : ObjectId("5e9c269d6c954c74be91e6dd"), "ClientName" : "Johnson" }
案例 1 −
以下是 / / 运算符的查询 −
> db.demo637.find({ClientName:/john/}).explain();
将产生以下输出 −
{ "queryPlanner" : { "plannerVersion" : 1, "namespace" : "test.demo637", "indexFilterSet" : false, "parsedQuery" : { "ClientName" : { "$regex" : "john" } }, "winningPlan" : { "stage" : "FETCH", "inputStage" : { "stage" : "IXSCAN", "filter" : { "ClientName" : { "$regex" : "john" } }, "keyPattern" : { "ClientName" : 1 }, "indexName" : "ClientName_1", "isMultiKey" : false, "multiKeyPaths" : { "ClientName" : [ ] }, "isUnique" : false, "isSparse" : false, "isPartial" : false, "indexVersion" : 2, "direction" : "forward", "indexBounds" : { "ClientName" : [ "[\"\", {})", "[/john/, /john/]" ] } } }, "rejectedPlans" : [ ] }, "serverInfo" : { "host" : "DESKTOP-QN2RB3H", "port" : 27017, "version" : "4.0.5", "gitVersion" : "3739429dd92b92d1b0ab120911a23d50bf03c412" }, "ok" : 1 }
案例 2 −
以下是 /^ / 运算符的查询 −
> db.demo637.find({ClientName:/^john/}).explain();
将产生以下输出 −
{ "queryPlanner" : { "plannerVersion" : 1, "namespace" : "test.demo637", "indexFilterSet" : false, "parsedQuery" : { "ClientName" : { "$regex" : "^john" } }, "winningPlan" : { "stage" : "FETCH", "inputStage" : { "stage" : "IXSCAN", "keyPattern" : { "ClientName" : 1 }, "indexName" : "ClientName_1", "isMultiKey" : false, "multiKeyPaths" : { "ClientName" : [ ] }, "isUnique" : false, "isSparse" : false, "isPartial" : false, "indexVersion" : 2, "direction" : "forward", "indexBounds" : { "ClientName" : [ "[\"john\", \"joho\")", "[/^john/, /^john/]" ] } } }, "rejectedPlans" : [ ] }, "serverInfo" : { "host" : "DESKTOP-QN2RB3H", "port" : 27017, "version" : "4.0.5", "gitVersion" : "3739429dd92b92d1b0ab120911a23d50bf03c412" }, "ok" : 1 }
广告