分片集群中Profiler必须在每个mongod分片节点和配置服务器上单独启用,mongos不支持;system.profile存在于各分片本地,需逐个连接查询。

分片集群不能在mongos上开Profiler
Profiler 必须在每个 mongod 分片节点(shard)和配置服务器(config server)上单独启用,mongos 节点不支持 Profiler 功能。如果你在 mongos 上执行 db.setProfilingLevel(),会直接报错:not master 或 command not supported。
- 分片集群中,
system.profile是每个数据库独立的 capped collection,只存在于具体分片的本地库中,mongos不存储也不代理 profiling 数据 - 所有 profiling 数据都分散在各 shard 的
system.profile中,不存在“全局慢查询视图”,必须逐个连接 shard 查询 - 副本集架构的 shard 需连到 primary 执行配置;config server 同样要单独开启(但通常 config server 负载低,profiling 可选关)
逐个分片启用Profiler的实操步骤
不能靠 mongos 统一下发,必须 SSH 登录每台 shard 机器,或通过 shell 直连对应 mongod 实例(端口通常是 27018/27019 等,非 mongos 的 27017):
- 连接 shard A:
mongosh --host shardA-host:27018 -u admin -p pwd --eval "db.getSiblingDB('your_db').setProfilingLevel(1, { slowms: 50 })" - 确认生效:
db.getSiblingDB('your_db').getProfilingLevel()—— 注意这里必须指定目标 DB,不能在 admin 库下查其他库的级别 - 若需记录所有操作(调试用),设为
2,但生产环境慎用:写入system.profile本身有开销,且 capped 集合默认仅 1MB,容易覆盖旧记录 - 对每个 shard 和 config server 重复上述操作;不要漏掉 secondary(它们不接受写,但 profiling 配置只在 primary 生效)
system.profile 大小不够怎么办
默认 system.profile 是 1MB 的 capped collection,高频写入下几秒就滚动覆盖。扩容必须在每个 shard 上分别操作,且需停 profiler:
- 先关闭:
db.getSiblingDB('your_db').setProfilingLevel(0) - 删旧集合:
db.getSiblingDB('your_db').system.profile.drop() - 重建(例如设为 10MB):
db.getSiblingDB('your_db').createCollection("system.profile", { capped: true, size: 10485760 }) - 重新启用:
db.getSiblingDB('your_db').setProfilingLevel(1, { slowms: 50 }) - 注意:副本集环境下,drop 和 create 操作必须在 primary 上执行,secondary 会自动同步;但操作期间 secondary 可能短暂不可读
查慢查询时必须指定分片和数据库
没有跨分片聚合的 system.profile 视图。你查不到“整个集群的慢查询”,只能查某个 shard 上某个 DB 的记录:
- 查 shardA 上
orders库最近 5 条慢操作:db.getSiblingDB('orders').system.profile.find().limit(5).sort({ts: -1}).pretty() - 查耗时 >100ms 的操作:
db.getSiblingDB('orders').system.profile.find({millis: {$gt: 100}}) - 时间范围过滤要用
ISODate,且注意各 shard 时钟是否一致(NTP 同步偏差大会导致时间查询错乱) - 如果业务逻辑涉及多分片路由(如未带 shard key 的查询),慢操作可能分散在多个 shard 上,得挨个查
最容易被忽略的是:分片键设计不合理时,一个慢查询可能广播到所有 shard,但 profiling 记录只留在各自 shard 的 system.profile 里,没人自动汇总——你得自己写脚本拉取、去重、排序。


















