且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MongoDB查询-关键顺序在复合索引的使用中是否重要

更新时间:2023-11-14 08:16:34

查询中键的顺序无关紧要:MongoDB足够聪明,可以查看所有查询的属性并找到一个合适的索引.

The order of keys in a query doesn't matter: MongoDB is smart enough to look at all the queried properties and find a suitable index.

但是,在索引中定义的键顺序确实很重要:复合索引可用于

However, the order of keys defined in an index does matter: a compound index can be used to match queries against any prefix of its keys, in the order they are defined in the index document. So your index above can be used to answer queries like {propA: 'x', propB: 'y'} but not queries like {propB: 'y', propC: 'z'}.

您可以使用 explain() 来找出MongoDB将用于特定查询的索引.

You can use explain() to figure out which index MongoDB is going to use for a specific query.