# 慢查询优化
* * * * *
--: 作者:Mick
时间:2018年10月9日
* * * * *
参考网址:https://blog.csdn.net/wmj2004/article/details/79415892
### 优化的思路
1. 用慢查询日志(system.profile)找到超过200ms的语句
2. 然后再通过.explain()解析影响行数,分析为什么超过200ms
3. 决定是不是需要添加索引
## 慢查询配置
#### 配置文件中开启
operationProfiling:
slowOpThresholdMs: 100
mode: slowOp
#### mongo shell 配置
> db.setProfilingLevel(1,200) // 1表示level,200表示慢查询时间(ms),(也可以省略时间设置{ "was" : 1, "slowms" : 100, "ok" : 1 } ---100表示之前的慢查询时间设定值,--was表示level级别)
> db.getProfilingStatus() // 查询当前慢查询的状态信息{ "was" : 1, "slowms" : 200 } ---was后的值表示级别
> db.getProfilingLevel() // 只查询Profiling级别可用此命令,级别 0 – 不开启 ,1 – 记录慢命令 (默认为>100ms),2 – 记录所有命令
> show profile //查看记录的system.profile信息
#### 删除慢查询文档
> db.setProfilingLevel(0) // 命令行先关闭
> db.system.profile.drop() // 删除集合
## system.profile日常使用的慢日志查询
#### 常用命令
> db.system.profile.find().limit(10).sort({ ts : -1 }).pretty() //返回最近的10条记录
> db.system.profile.find( { op: { $ne : ‘command‘ } }).pretty() //返回所有的操作,除command类型的
> db.system.profile.find( { ns : ‘mydb.test‘ } ).pretty() //返回特定集合
> db.system.profile.find({ millis : { $gt : 5 } } ).pretty() //返回大于5毫秒慢的操作
> db.system.profile.find().sort({$natural:-1}).limit(1) //查看最新的 Profile 记录
> show profile // 显示5个最近的事件
>db.system.profile.find( {
ts : {
$gt : newISODate("2018-10-12T03:00:00Z") ,
$lt : newISODate("2018-10-12T03:40:00Z")
} }).sort( { millis : -1 } ) //特定时间按照消耗时间排序
// db.system.profile.find({ts : {$gt : new Date(2018,9,10,9)} }).pretty()
## 针对语句分析
> db.collectionName.find().explain() // 查看执行情况