MongoDB复合索引用法 [英] MongoDB compound index usage
问题描述
假设我有以下两个密钥的文件:
Lets say I have document with the following two keys:
1)key1
2)key2
1) key1
2) key2
如果我在两者上创建复合索引..
If I am creating compound index on both of them..
{'key1':1,'key2':1}
运行时只与key1相关的查询是否使用了上面的索引?或者我还需要为key1创建特定的索引?
When running a query relevant only for key1.. does the index above is used? or I need to create specific index only for key1 also?
谢谢
推荐答案
是。在B树索引中,您可以使用列的前缀。
Yes. In a B-tree index, you can use a prefix of the columns.
因此,您可以在'key1'上使用索引进行查询(但不能有效地使用'key2',索引中的列顺序很重要。)
So you can use the index for a query on 'key1' (but not as efficiently for 'key2', the column order in the index matters).
这与打印电话簿中的情况相同,后者是[lastName,firstName]的索引。您可以使用它来轻松地通过lastName查找人员(而不是通过firstName轻松查找人员,但仍然比调用所有人并询问他们的名字更有效。)
This is the same situation as in a printed telephone book, which is an index on [lastName, firstName]. You can use that to look up people by lastName easily (and not so easily by firstName, but still more efficient than calling everyone and asking for their first name).
这篇关于MongoDB复合索引用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!