MongoDB : Indexes order and query order must match?

后端 未结 2 431
生来不讨喜
生来不讨喜 2020-12-15 17:18

This question concern the internal method to manage indexes and serching Bson Documents.

When you create a multiple indexes like \"index1\", \"index2\", \"index3\"..

相关标签:
2条回答
  • 2020-12-15 17:30

    From http://www.mongodb.org/display/DOCS/Indexes:

    If you have a compound index on multiple fields, you can use it to query on the beginning subset of fields. So if you have an index on

    a,b,c

    you can use it query on

    a

    a,b

    a,b,c

    So yes, order matters. You should clarify your question a bit if you need a more precise answer.

    0 讨论(0)
  • 2020-12-15 17:40

    The order of the conditions in your query does not affect whether it can use an index or no.

    e.g. typical document structure:

    {
        "FieldA" : "A",
        "FieldB" : "B"
    }
    

    If you have an compound index on A and B :

    db.MyCollection.ensureIndex({FieldA : 1, FieldB : 1})
    

    Then both of the following queries will be able to use that index:

    db.MyCollection.find({FieldA : "A", FieldB : "B"})
    db.MyCollection.find({FieldB : "B", FieldA : "A"})
    

    So the ordering of the conditions in the query do not prevent the index being used - which I think is the question you are asking.

    You can easily test this out by trying the 2 queries in the shell and adding .explain() after the find. I just did this to confirm, and they both showed that the compound index was used.

    however, if you run the following query, this will NOT use the index as FieldA is not being queried on:

    db.MyCollection.find({FieldB : "B"})
    

    So it's the ordering of the fields in the index that defines whether it can be used by a query and not the ordering of the fields in the query itself (this was what Lucas was referring to).

    0 讨论(0)
提交回复
热议问题