簡介
使用Mysql數據庫的朋友,肯定知道,可以開啟慢查詢日志,就能捕獲Mysql數據庫中的慢SQL語句了,那么在Mongo數據庫怎么捕獲慢查詢呢mongo查詢大量數據慢,下面就一步步帶大家了解Mongo數據庫的慢查詢功能的開啟和使用的。
開啟Mongo數據庫的慢查詢功能
Mongo數據庫的慢查詢功能()有三個級別 0:代表關閉,不收集任何慢查詢 1:收集慢查詢數據,默認收集超過100毫秒的慢查詢 2:收集任何操作記錄數據
默認情況下,Mongo數據庫的慢查詢功能是關閉的,如果想要知道Mongo數據庫是否已經開啟慢查詢功能,可以通過下面命令
> db.getProfilingLevel()
0
可以看到返回結果是0,Mongo數據庫沒有開啟慢查詢功能。
開啟Mongo數據庫的慢查詢功能 在這里需要注意,Mongo數據庫的慢查詢數據是存放在一個數據庫集合中(.),這個和Mysql數據庫是有區別的,如果你不主動創建.這個集合,那這個集合就固定1M大小,當慢查詢記錄超過1M,就會將歷史數據覆蓋,循環使用,所以在這里需要根據業務實際情況設置集合大小。
在這里需要大家注意的是,.在哪個數據庫下創建mongo查詢大量數據慢,就只會收集這個數據庫下的慢查詢,在這里,我在test數據庫下創建.集合,操作過程如下所示
> use test
switched to db admin
> db.createCollection( "system.profile", { capped: true, size: 1024*1024*10 } )
{ "ok" : 1 }
> show tables;
customers
system.profile
user
開啟慢查詢功能
> db.setProfilingLevel(1, { slowms: 500 })
{ "was" : 0, "slowms" : 100, "sampleRate" : 1, "ok" : 1 }
> db.getProfilingStatus()
{ "was" : 1, "slowms" : 500, "sampleRate" : 1 }
這里設置的級別為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" : "" }
從上面結果可以看到,已經捕獲到慢查詢了。