Mongodb query - Does sequence of key matters in us

2019-07-25 13:16发布

问题:

Suppse I created index like following :-

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

and I query like following :-

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

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

回答1:

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.

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'}.

You can use explain() to figure out which index MongoDB is going to use for a specific query.



回答2:

To add to Avish's answer, such an index comprising of more than one fields is called a compound index. The order of the fields listed in a compound index is quite important. Here is why:

The index will contain references to documents sorted first by the values of the first field and, within each value of the first field, sorted by values of the second field and, within each value of the second field, sorted by values of the third field, and so on.

For example in your case, index will contain references to documents sorted first by the values of the propA field and, within each value of the propA field, sorted by values of the propB field and, within each value of the propB field, sorted by values of the propC field.

So keep in mind that while following queries will use the given index:

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

The following can't use the given index:

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