如何在mongodb中查找不使用索引或缓慢的查询

时间:2013-08-26 19:34:28

标签: performance mongodb mongodb-query

有没有办法在mongodb中查找不使用索引或缓慢的查询?在MySQL中,配置文件中可以使用以下设置:

log-queries-not-using-indexes = 1
log_slow_queries = /tmp/slowmysql.log

6 个答案:

答案 0 :(得分:18)

MongoDB中的等效方法是使用query profiler来跟踪和诊断慢速查询。

对数据库启用分析后,会将慢速操作写入system.profile上限集合(默认情况下为1Mb)。您可以使用slowms parameter调整慢速操作的阈值(默认为100毫秒)。

答案 1 :(得分:14)

首先,您必须设置性能分析,指定所需的日志级别。 3个选项是:

  • 0 - 关闭记录器
  • 1 - 记录慢查询
  • 2 - 记录所有查询

您可以通过mongod选项运行--profile守护来执行此操作:

mongod --profile 2 --slowms 20

这样,日志将被写入system.profile集合,您可以在其上执行查询,如下所示:

  • 查找某些集合中的所有日志,按升序时间戳排序:

db.system.profile.find( { ns:/<db>.<collection>/ } ).sort( { ts: 1 } );

  • 查找超过5毫秒的查询日志:

db.system.profile.find( {millis : { $gt : 5 } } ).sort( { ts: 1} );

答案 2 :(得分:6)

您可以使用以下两个mongod选项。第一个选项无法使用不使用索引的查询(仅限V 2.4),第二个选项记录查询慢于某个ms阈值(默认为100毫秒)

--notablescan

Forbids operations that require a table scan.

--slowms <value>

Defines the value of “slow,” for the --profile option. The database logs all slow queries to the log, even when the profiler is not turned on. When the database profiler is on, mongod the profiler writes to the system.profile collection. See the profile command for more information on the database profiler.

答案 3 :(得分:3)

您可以使用命令行工具mongotail在控制台中以更易读的格式从分析器中读取日志。

首先激活探查器并设置阈值(以毫秒为单位),以使配置文件认为操作较慢。在以下示例中,名为“sales”的数据库的阈值设置为10毫秒:

$ mongotail sales -l 1
Profiling level set to level 1
$ mongotail sales -s 10
Threshold profiling set to 10 milliseconds

然后,在“实时”中查看慢速查询,以及一些额外信息,例如每个查询所花费的时间,或者需要“走”以查找特定结果的注册表数量:

$ mongotail sales -f -m millis nscanned docsExamined
2016-08-11 15:09:10.930 QUERY   [ops] : {"deleted": {"$exists": false}, "prod_id": "367133"}. 8 returned. nscanned: 344502. millis: 12
2016-08-11 15:09:10.981 QUERY   [ops] : {"deleted": {"$exists": false}, "prod_id": "367440"}. 6 returned. nscanned: 345444. millis: 12
....

答案 4 :(得分:1)

如果有人在这个旧问题上从谷歌结束,我发现explain确实帮助我修复了我可以看到的日志中导致COLLSCAN的特定查询。

示例:

db.collection.find().explain()

这将告诉您查询是使用COLLSCAN(基本光标)还是index(BTree)等。

https://docs.mongodb.com/manual/reference/method/cursor.explain/

答案 5 :(得分:-5)

虽然你明显可以使用Profiler一个非常简洁的Mongo DB功能,因为我真的爱上它是Mongo DB MMS。 耗时少于60秒,可以随时随地进行管理。我相信你一定会喜欢它。 https://mms.mongodb.com/