从 profiler 数据中提取最慢的查询和查询形态
MongoDB性能命令
// Recent slow operations (in the db where profiling is on; see set-profiling):
db.system.profile.find({ millis: { $gte: 100 } }, { ts: 1, ns: 1, op: 1, millis: 1, planSummary: 1, keysExamined: 1, docsExamined: 1, nreturned: 1, appName: 1 }).sort({ ts: -1 }).limit(20)
// Total time per query shape (those consuming the most time):
db.system.profile.aggregate([
{ $group: { _id: { ns: "$ns", plan: "$planSummary", shape: "$queryHash" }, n: { $sum: 1 }, totalMs: { $sum: "$millis" }, maxMs: { $max: "$millis" }, avgDocs: { $avg: "$docsExamined" } } },
{ $sort: { totalMs: -1 } },
{ $limit: 10 }
])
// Queries not using an index (COLLSCAN):
db.system.profile.find({ planSummary: "COLLSCAN" }, { ns: 1, millis: 1, command: 1 }).sort({ millis: -1 }).limit(10)作用
根据 system.profile 集合中的记录,列出最近的慢操作、每种查询形态(queryHash)的总耗时,以及未使用索引的 COLLSCAN 查询。
适用场景
出现变慢投诉时,用于找出哪个查询消耗了服务器时间并确定索引需求。
注意
system.profile 默认是 1 MB 的 capped 集合,且按数据库区分;在繁忙系统上记录几分钟内就会被覆盖,因此要在 profiling 开启期间或刚结束后分析。profiling 级别 2 或 slowms 0 会写入每个操作,开销显著。记录只保存在执行操作的成员上,不会被复制。