第35章 MongoDB 查询分析教程
第35章 MongoDB 查询分析教程可以确保咱们所建立的索引是否有效,是查询语句性能分析的重要tool 。
第35章 MongoDB 查询分析教程常用函数有:explain() 和 hint()。
使用 explain()
explain 操作提供了查询信息,使用索引及查询统计等。有利于咱们对索引的优化。
接下来咱们在 users 集合中创建 gender 和 user_name 的索引:
>db.users.ensureIndex({gender:1,user_name:1})
现在在查询语句中使用 explain :
>db.users.find({gender:"M"},{user_name:1,_id:0}).explain()
以上的 explain() 查询return 如下结果请在输出结果查看
{
"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
}
]
]
}
}
现在,咱们看看这个结果集的字段:
- indexOnly: 字段为 true ,表示咱们使用了索引。
- cursor:因为这个查询使用了索引,MongoDB 中索引存储在B树结构中,所以这是也使用了 BtreeCursor 类型的游标。如果没有使用索引,游标的类型是 BasicCursor。这个键还会给出陛下所使用的索引的名称,陛下通过这个名称可以查看当前database下的system.indexes集合(系统自动创建,由于存储索引信息,这个稍微会提到)来得到索引的详细信息。
- n:当前查询return 的文档数量。
- nscanned/nscannedObjects:表明当前这次查询一共扫描了集合中多少个文档,咱们的目的是,让这个数值和return 文档的数量越接近越好。
- millis:当前查询所需时间,毫秒数。
- indexBounds:当前查询具体使用的索引。
使用 hint()
虽然MongoDB查询优化器一般工作的很不错,但是也可以使用 hint 来强制 MongoDB 使用一个指定的索引。
这种方法某些情形下会提升性能。 一个有索引的 collection 并且执行一个多字段的查询(一些字段已经索引了)。
如下查询实例指定了使用 gender 和 user_name 索引字段来查询:
>db.users.find({gender:"M"},{user_name:1,_id:0}).hint({gender:1,user_name:1})
可以使用 explain() 函数来分析以上查询:
>db.users.find({gender:"M"},{user_name:1,_id:0}).hint({gender:1,user_name:1}).explain()
本专栏所有文章
第1章 MongoDB 教程 | 第2章 NoSQL 简介教程 |
---|---|
第3章 MongoDB 简介教程 | 第4章 Windows MongoDB教程 |
第5章 Linux MongoDB教程 | 第6章 OSX MongoDB教程 |
第7章 MongoDB 概念解析教程 | 第8章 MongoDB 连接教程 |
第9章 MongoDB 创建数据库教程 | 第10章 MongoDB 删除数据库教程 |
第11章 MongoDB 创建集合教程 | 第12章 MongoDB 删除集合教程 |
第13章 MongoDB 插入文档教程 | 第14章 MongoDB 更新文档教程 |
第15章 MongoDB 删除文档教程 | 第16章 MongoDB 查询文档教程 |
第17章 MongoDB 条件操作符教程 | 第18章 MongoDB $type 操作符教程 |
第19章 MongoDB Limit与Skip方法教程 | 第20章 MongoDB 排序教程 |
第21章 MongoDB 索引教程 | 第22章 MongoDB 聚合教程 |
第23章 MongoDB 复制(副本集)教程 | 第24章 MongoDB 分片教程 |
第25章 MongoDB 备份与恢复教程 | 第26章 MongoDB 监控教程 |
第27章 MongoDB Java教程 | 第28章 MongoDB PHP 扩展教程 |
第29章 MongoDB PHP教程 | 第30章 MongoDB PHP7教程 |
第31章 Node.js MongoDB教程 | 第32章 MongoDB 关系教程 |
第33章 MongoDB 数据库引用教程 | 第34章 MongoDB 覆盖索引查询教程 |
第35章 第35章 MongoDB 查询分析教程教程 | 第36章 MongoDB 原子操作教程 |
第37章 MongoDB 高级索引教程 | 第38章 MongoDB 索引限制教程 |
第39章 MongoDB ObjectId教程 | 第40章 MongoDB Map Reduce教程 |
第41章 MongoDB 全文检索教程 | 第42章 MongoDB 正则表达式教程 |
第43章 MongoDB 管理工具教程 | 第44章 MongoDB GridFS教程 |
第45章 MongoDB 固定集合教程 | 第46章 MongoDB 自动增长教程 |
寄语
本文有榴莲酱CSDN原创,欢迎点赞、转载,博客地址:https://blog.csdn.net/qq441540598
- 我们不会为了所谓的尊严在自己弱小时攻击比自己强大的东西。我们如果不得不面对比自己强大的东西,必群起而攻之。
- 当爱情缺席的时候,学着过自己的生活。过自己的生活,就是跟自己谈恋爱,把自己当成自己的情人那样,好好宠自己。
- 面对危机别无选择时,我们就一定要勇于毅然杀出一条血路来以求绝处逢生。
- 世界上有许多种遇见,最美好的,莫过于,在我最美的时光里与你相遇。
- 一日为师,终身为父。[中国·汉代史学家]司马迁