MongoDB 优化器MongoDB Database Profiler(12)

2023-03-18,,

优化器profile

在MySQL 中,慢查询日志是经常作为我们优化数据库的依据,那在MongoDB 中是否有类似的功能呢?答案是肯定的,那就是MongoDB Database Profiler。

1.开启profiling功能

有两种方式可以控制 Profiling 的开关和级别,第一种是直接在启动参数里直接进行设置。启动MongoDB 时加上–profile=级别 即可。也可以在客户端调用db.setProfilingLevel(级别) 命令来实时配置,Profiler 信息保存在system.profile 中。我们可以通过db.getProfilingLevel()命令来获取当前的Profile 级别,类似如下操作:

db.setProfilingLevel(2);

上面profile 的级别可以取0,1,2 三个值,他们表示的意义如下:

1.0 – 不开启
2.1 – 记录慢命令 (默认为>100ms)
3.2 – 记录所有命令

Profile 记录在级别1 时会记录慢命令,那么这个慢的定义是什么?上面我们说到其默认为100ms,当然有默认就有设置,其设置方法和级别一样有两种,一种是通过添加 –slowms 启动参数配置。第二种是调用db.setProfilingLevel 时加上第二个参数:

db.setProfilingLevel( level , slowms )
db.setProfilingLevel( 1 , 10 );

2.查询 Profiling 记录

与MySQL 的慢查询日志不同,MongoDB Profile 记录是直接存在系统db 里的,记录位置system.profile ,所以,我们只要查询这个Collection 的记录就可以获取到我们的 Profile 记录了。列出执行时间长于某一限度(5ms)的 Profile 记录:

db.system.profile.find( { millis : { $gt : 5 } } )

MongoDB Shell 还提供了一个比较简洁的命令show profile,可列出最近5 条执行时间超过1ms 的 Profile 记录。

3.删除Profiling记录

//删除
db.setProfilingLevel(0)
db.system.profile.drop()

MongoDB 优化器MongoDB Database Profiler(12)的相关教程结束。

《MongoDB 优化器MongoDB Database Profiler(12).doc》

下载本文的Word格式文档,以方便收藏与打印。