标题:mongodb 优化器 profile 出处:BIWEB开源PHP WMS系统创始人ArthurXF肖飞的blog 时间:Fri, 26 Oct 2012 11:23:55 +0000 作者:ArthurXF 地址:http://www.bizeway.net/read.php/607.htm 内容: 在MySQL 中,慢查询日志是经常作为我们优化数据库的依据,那在MongoDB 中是否有类似 的功能呢?答案是肯定的,那就是MongoDB Database Profiler。所以MongoDB 不仅有,而且 还有一些比MySQL 的Slow Query Log 更详细的信息。 1. 开启 Profiling 功能 有两种方式可以控制 Profiling 的开关和级别,第一种是直接在启动参数里直接进行设置。 启动MongoDB 时加上–profile=级别 即可。 也可以在客户端调用db.setProfilingLevel(级别) 命令来实时配置,Profiler 信息保存在 system.profile 中。我们可以通过db.getProfilingLevel()命令来获取当前的Profile  级别,类似如下操作 > db.setProfilingLevel(2);{ "was" : 0, "slowms" : 100, "ok" : 1 } 上面profile 的级别可以取0,1,2 三个值,他们表示的意义如下:  0 – 不开启  1 – 记录慢命令 (默认为>100ms)  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 } } ) 查看最新的 Profile 记录: db.system.profile.find().sort({$natural:-1}).limit(1) > db.system.profile.find().sort({$natural:-1}).limit(1){ "ts" : ISODate("2012-05-20T16:50:36.321Z"), "info" : "query test.system.profile reslen:1219nscanned:8 \nquery: { query: {}, orderby: { $natural: -1.0 } } nreturned:8 bytes:1203", "millis" :0 }> 字段说明:  ts: 该命令在何时执行  info: 本命令的详细信息  reslen: 返回结果集的大小  nscanned: 本次查询扫描的记录数  nreturned: 本次查询实际返回的结果集  millis: 该命令执行耗时,以毫秒记 MongoDB Shell 还提供了一个比较简洁的命令show profile,可列出最近5 条执行时间超过 1ms 的 Profile 记录。 Generated by Bo-blog 2.0.3 sp1