MongoDB compound index usage

前端 未结 2 1997
粉色の甜心
粉色の甜心 2020-12-19 13:48

Lets say I have document with the following two keys:

1) key1
2) key2

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

         


        
2条回答
  •  天涯浪人
    2020-12-19 14:22

    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

提交回复
热议问题