下面是"MongoDB如何查询耗时记录的方法详解"的完整攻略.
MongoDB提供了多种性能分析工具,可以帮助开发者更好地快速分析查询性能,解决各种慢查询问题.
其中最常用的性能分析工具是:mongotop,mongostat和slow query log.
mongotop用来监控MongoDB实例中的写入操作.它会显示出每个集合中的插入、更新和删除操作的QPS.可以使用 mongotop 命令在Linux/Unix下启动.
mongostat 用来监控MongoDB实例中的各种指标,如连接数、插入、查询等操作次数,平均响应时间,缓存命中率等等.
slow query log 可以记录下慢查询的详细信息,如执行时间,命中索引情况等.开发者可以利用这些信息来定位性能问题.需要在MongoDB配置中开启 slow query log 功能.
对于MongoDB,如果我们想要查询耗时操作的记录,可以使用MongoDB原生特性——系统集合system.profile.
当开启profiling时,MongoDB会把每次查询操作的执行时间、命中索引情况等详细信息写入到system.profile集合中.
我们可以通过以下方式查询system.profile集合获取查询耗时的记录:
先打开MongoDB的命令行,进入到目标数据库中
执行以下命令开启query profiling:
db.setProfilingLevel(2)
然后执行一个慢查询语句,例如:
db.collection.find({field: value}).limit(10).sort({field: -1})
最后查询system.profile集合获取查询记录:
db.system.profile.find().sort({ts: -1}).limit(10)
其中,ts是执行时间,在system.profile中作为索引字段使用.
这样就可以获取最近10次慢查询的详细信息,从而进行性能优化.
下面以具体的示例说明如何利用system.profile集合来查询耗时记录.
mongos> use test
switched to db test
mongos> db.setProfilingLevel(2)
{ "was" : 0, "slowms" : 100 }
mongos> db.student.find({age:{$gte:20}})
查询完毕后,我们可以使用以下命令查询system.profile集合中记录的操作:
mongos> db.system.profile.find().pretty()
输出结果如下:
{
"op" : "query",
"ns" : "test.student",
"command" : {
"find" : "student",
"filter" : {
"age" : {
"$gte" : 20
}
}
},
"keysExamined" : 0,
"docsExamined" : 3000000,
"cursorExhausted" : true,
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 3000000,
"executionTimeMillis" : 4745,
"totalKeysExamined" : 0,
"totalDocsExamined" : 3000000,
"executionStages" : {
"stage" : "COLLSCAN",
"nReturned" : 3000000,
"executionTimeMillisEstimate" : 3619,
"works" : 3000002,
"advanced" : 3000000,
"needTime" : 1,
"needYield" : 0,
"saveState" : 23311,
"restoreState" : 23311,
"isEOF" : 1,
"direction" : "forward",
"docsExamined" : 3000000
}
},
"ts" : ISODate("2022-02-11T05:05:51.204Z"),
"client" : "12⑦0.0.1",
"allUsers" : [ ],
"user" : ""
}
从输出结果中可以看到,MongoDB记录了查询操作的详细信息,包括查询的条件、执行时间、命中索引情况等等.其中,executionTimeMillis表示执行时间,totalDocsExamined表示扫描的document数.
通过对这些信息的分析,我们可以进一步优化查询性能,避免重复扫描等影响性能的操作.
参考资料:
MongoDB官方文档:https://docs.mongodb.com/manual/tutorial/manage-the-database-profiler/
以上就是土嘎嘎小编为大家整理的MongoDB如何查询耗时记录的方法详解相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!