mongo官方文档对hint的解释如下:
The $hint operator forces the query optimizer to use a specific index to fulfill the query. Specify the index either by the index name or by document.
hint的命令行用法:
db.users.find().hint()
mongo中使用explain来确定查询使用的索引方案,对比explain的结果,可以反向校验hint的使用。explain的命令行用法:
db.collection.explain()
github.com/globalsign/mgo下对hint方法的注释如下:
// Hint will include an explicit "hint" in the query to force the server
// to use a specified index, potentially improving performance in some
// situations. The provided parameters are the fields that compose the
// key of the index to be used. For details on how the indexKey may be
// built, see the EnsureIndex method.
hint参数列表是用作索引的字段,更多细节请参考EnsureIndex方法。
// To obtain an index with a descending order,
// the field name should be prefixed by a dash
组合索引
mongo中组合索引称为Compound Index,不同于MySQL,它可以指定索引字段排列顺序。对于下面的索引:
{ userid: 1, score: -1 }
索引先通过userid进行排序,如果user_id相同,再根据score的倒序排。这中形式,对查询有什么影响呢?
从mongo官方文档的例子来尝试理解,索引{ a: 1, b: -1 }支持{ a: 1, b: -1 }和{ a: -1, b: 1 }的排序操作,但不支持{ a: -1, b: -1 }和{a: 1, b: 1}的操作。