本文介绍了MongoDB查询-关键顺序在复合索引的使用中是否重要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

补充我创建了如下索引:-

Suppse I created index like following :-

db.collection.createIndex( { propA: 1, propB: 1, propC:1 } )

我查询如下:-

db.collection.find({propB:'x', propC: 'y', propA:'z'})

mongo查询引擎是否使用上面创建的索引.编写查询时,键顺序对复合索引的用法有影响吗?

will mongo query engine use the index created above or not.Does sequence of key matters in usage of compound index while writing query?

推荐答案

查询中键的顺序无关紧要: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.

但是,在索引中定义的键顺序确实很重要:复合索引可用于将查询与键的任何前缀匹配,以在索引文档中定义的顺序进行.因此,上面的索引可用于回答诸如{propA: 'x', propB: 'y'}之类的查询,但不能回答诸如{propB: 'y', propC: 'z'}之类的查询.

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.

这篇关于MongoDB查询-关键顺序在复合索引的使用中是否重要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:47
查看更多