# 慢查詢優化
* * * * *
--: 作者: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() // 查看執行情況