执行计划
MongoDB 查询分析可以确保我们建议的索引是否有效,是查询语句性能分析的重要工具
#插入1000条数据
for(var i=1;i<1000;i++)db.user.insert({id:100+i,username:'name_'+i,age:10+i})
#查看执行计划
> db.user.find({age:{$gt:100},id:{$lt:200}}).explain()
{"queryPlanner" : {"plannerVersion" : 1,"namespace" : "testdb.user","indexFilterSet" : false,"parsedQuery" : {"$and" : [{"id" : {"$lt" : 200}},{"age" : {"$gt" : 100}}]},"winningPlan" : { #最佳执行计划"stage" : "FETCH", #查询方式,常见的有COLLSCAN/全表扫描、IXSCAN/索引扫描、FETCH/根据索引去检索文档、SHARD_MERGE/合并分片结果、IDHACK/针对_id进行查询"inputStage" : {"stage" : "IXSCAN","keyPattern" : {"age" : 1,"id" : -1},"indexName" : "age_1_id_-1","isMultiKey" : false,"multiKeyPaths" : {"age" : [ ],"id" : [ ]},"isUnique" : false,"isSparse" : false,"isPartial" : false,"indexVersion" : 2,"direction" : "forward","indexBounds" : {"age" : ["(100.0, inf.0]"],"id" : ["(200.0, -inf.0]"]}}},"rejectedPlans" : [ ]},"serverInfo" : {"host" : "c493d5ff750a","port" : 27017,"version" : "4.0.3","gitVersion" : "7ea530946fa7880364d88c8d8b6026bbc9ffa48c"},"ok" : 1
}
#测试没有使用索引
> db.user.find({username:'zhangsan'}).explain()
{"queryPlanner" : {"plannerVersion" : 1,"namespace" : "testdb.user","indexFilterSet" : false,"parsedQuery" : {"username" : {"$eq" : "zhangsan"}},"winningPlan" : {"stage" : "COLLSCAN", #全表扫描"filter" : {"username" : {"$eq" : "zhangsan"}},"direction" : "forward"},"rejectedPlans" : [ ]},"serverInfo" : {"host" : "c493d5ff750a","port" : 27017,"version" : "4.0.3","gitVersion" : "7ea530946fa7880364d88c8d8b6026bbc9ffa48c"},"ok" : 1
}