开启Mongo数据库的慢查询功能
Mongo数据库的慢查询功能(Profiling)有三个级别0:代表关闭,不网络任何慢查询1:网络慢查询数据,默认网络超过100毫秒的慢查询2:网络任何操作记录数据
默认情形下,Mongo数据库的慢查询功能是关闭的,如果想要知道Mongo数据库是否已经开启慢查询功能,可以通过下面命令
> db.getProfilingLevel()0
可以看到返回结果是0,Mongo数据库没有开启慢查询功能。

开启Mongo数据库的慢查询功能在这里须要把稳,Mongo数据库的慢查询数据是存放在一个数据库凑集中(system.profile),这个和Mysql数据库是有差异的,如果你不主动创建system.profile这个凑集,那这个凑集就固定1M大小,当慢查询记录超过1M,就会将历史数据覆盖,循环利用,以是在这里须要根据业务实际情形设置凑集大小。
在这里须要大家把稳的是,system.profile在哪个数据库下创建,就只会网络这个数据库下的慢查询,在这里,我在test数据库下创建system.profile凑集,操作过程如下所示
> use testswitched to db admin> db.createCollection( "system.profile", { capped: true, size: 1024102410 } ){ "ok" : 1 }> show tables;customerssystem.profileuser
开启慢查询功能
> db.setProfilingLevel(1, { slowms: 500 }){ "was" : 0, "slowms" : 100, "sampleRate" : 1, "ok" : 1 }> db.getProfilingStatus(){ "was" : 1, "slowms" : 500, "sampleRate" : 1 }
这里设置的Profiling级别为1,慢查询阈值为500毫秒。
慢查询功能测试这里为了方便测试,将慢查询的级别设置为2
> db.setProfilingLevel(2){ "was" : 1, "slowms" : 500, "sampleRate" : 1, "ok" : 1 }> db.getProfilingStatus(){ "was" : 2, "slowms" : 500 "sampleRate" : 1 }
仿照凑集的查询
> db.user.find(){ "_id" : ObjectId("5fbf52c182be1e071c0db8ef"), "username" : "jim", "age" : 18, "status" : 0 }{ "_id" : ObjectId("5fbf530082be1e071c0db8f0"), "username" : "tony", "age" : 28, "status" : 0 }{ "_id" : ObjectId("5fbf530082be1e071c0db8f1"), "username" : "trace" }{ "_id" : ObjectId("5fbf53b382be1e071c0db8f2"), "username" : "tony1" }{ "_id" : ObjectId("5fbf53b382be1e071c0db8f3"), "username" : "trace1" }> db.system.profile.find(){ "op" : "query", "ns" : "test.user", "command" : { "find" : "user", "filter" : { }, "lsid" : { "id" : UUID("7424ffd1-52d9-48b1-b658-9adfd3189a89") }, "$db" : "test" }, "keysExamined" : 0, "docsExamined" : 5, "cursorExhausted" : true, "numYield" : 0, "nreturned" : 5, "locks" : { "ReplicationStateTransition" : { "acquireCount" : { "w" : NumberLong(1) } }, "Global" : { "acquireCount" : { "r" : NumberLong(1) } }, "Database" : { "acquireCount" : { "r" : NumberLong(1) } }, "Collection" : { "acquireCount" : { "r" : NumberLong(1) } }, "Mutex" : { "acquireCount" : { "r" : NumberLong(1) } } }, "flowControl" : { }, "responseLength" : 379, "protocol" : "op_msg", "millis" : 0, "planSummary" : "COLLSCAN", "execStats" : { "stage" : "COLLSCAN", "nReturned" : 5, "executionTimeMillisEstimate" : 0, "works" : 7, "advanced" : 5, "needTime" : 1, "needYield" : 0, "saveState" : 0, "restoreState" : 0, "isEOF" : 1, "direction" : "forward", "docsExamined" : 5 }, "ts" : ISODate("2020-12-03T09:49:45.211Z"), "client" : "127.0.0.1", "appName" : "MongoDB Shell", "allUsers" : [ ], "user" : "" }
从上面结果可以看到,已经捕获到慢查询了。
关注1.如果您喜好这篇文章,请点赞+转发。
2.如果您特殊喜好,请加关注。