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

Dmi*_*nov 23 performance mongodb mongodb-query

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

log-queries-not-using-indexes = 1
log_slow_queries = /tmp/slowmysql.log
Run Code Online (Sandbox Code Playgroud)

Ste*_*nie 19

MongoDB中的等效方法是使用查询分析器来跟踪和诊断慢速查询.

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

  • 或者,您可以执行以下操作:mongo localhost:27017并在控制台中写入db.setProfilingLevel(2,10)-这将在日志中打印所有耗时超过10毫秒的查询 (2认同)

Raf*_*yng 14

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

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

你通过运行你的mongoddeamon --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} );


Ori*_*Dar 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.
Run Code Online (Sandbox Code Playgroud)


Mar*_*uiz 5

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

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

$ mongotail sales -l 1
Profiling level set to level 1
$ mongotail sales -s 10
Threshold profiling set to 10 milliseconds
Run Code Online (Sandbox Code Playgroud)

然后,要“实时”查看缓慢的查询,以及一些额外的信息,例如每个查询花费的时间,或者需要“遍历”多少个注册表才能找到特定结果:

$ 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
....
Run Code Online (Sandbox Code Playgroud)