MongoDB强制使用索引hint

MongoDB强制使用索引hint教程

虽然 MongoDB 查询优化器一般工作的很不错,但是也可以使用 hint() 来强迫 MongoDB 使用一个特定的索引。在这种方法下某些情形下会提升性能。

一个有索引的 collection 并且执行一个多字段的查询。传入一个制定的索引,强迫查询使用该索引。

MongoDB强制使用索引hint详解

语法

db_name.table_name.find({query}).hint({"index_name":1});

参数

名称 描述
db_name 数据库名
table_name 集合名
query 查询条件
index_name 索引名

说明

这里,我们在使用 query 条件查询时,强制使用 index_name 索引。

案例

我们首先,使用 mongo 命令,连接上数据库,具体命令如下:

mongo

如下图所示:

70_MongoDB强制使用索引hint.png

现在,我们使用 use 命令,切换到 haicoder 数据库,具体命令如下:

use haicoder

现在,我们使用 insert 插入记录,具体命令如下:

db.haicoder.insert([ {id:1, "url" : "haicoder.net/c", "score" : 100 }, {id:2, "url" : "haicoder.net/cpp", "score" : 90 }, {id:3, "url" : "haicoder.net/golang", "score" : 80 }, {id:4, "url" : "haicoder.net/java", "score" : 60 } ]);

执行完毕后,此时,如下图所示:

71_MongoDB强制使用索引hint.png

我们看到,此时提示我们成功插入了多条记录,现在,我们创建一个 score 索引,具体命令如下:

db.haicoder.ensureIndex({"score": 1});

执行完毕后,如下图所示:

72_MongoDB强制使用索引hint.png

现在,我们查询强制使用索引,具体命令如下:

db.haicoder.find({socre:{$gt:80}}).hint("score_1").explain()

执行完毕后,此时,如下图所示:

73_MongoDB强制使用索引hint.png

我们看到,此时,查询使用了索引。

MongoDB强制使用索引hint总结

虽然 MongoDB 查询优化器一般工作的很不错,但是也可以使用 hint() 来强迫 MongoDB 使用一个特定的索引。在这种方法下某些情形下会提升性能。

一个有索引的 collection 并且执行一个多字段的查询。传入一个制定的索引,强迫查询使用该索引。