MongoDB compound index usage

安稳与你 提交于 2019-11-28 04:11:46

问题


Lets say I have document with the following two keys:

1) key1
2) key2

If I am creating compound index on both of them..

{'key1':1,'key2':1}

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?

Thanks


回答1:


Yes. In a B-tree index, you can use a prefix of the columns.

So you can use the index for a query on 'key1' (but not as efficiently for 'key2', the column order in the index matters).

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).




回答2:


In MongoDB, you can use index prefix to query the database. You can't use anything else. If your query does not contain key prefix the index won't be used.

Assuming your proposed index {'key1':1,'key2':1}:

Queries that will use index:

  • db.some.find({key1 : {$gt : 100}}) - uses prefix
  • db.some.find({key1 : {$gt : 100}, key2 : {$lt : 30}}) - uses full index
  • db.some.find({key3 : 'test'}).sort({key1 : 1}) - uses prefix for sort (direction match)

Queries that will NOT use index:

  • db.some.find({key2 : {$gt : 100}}) - index order matters - key2 is not prefix
  • db.some.find({key3 : 'test'}).sort({key1 : -1}) - index direction matters for multicolumn indexes
  • db.some.find({key3 : 'test'}).sort({key2 : 1}) - it's not prefix


来源:https://stackoverflow.com/questions/17735279/mongodb-compound-index-usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!