0

In the mongodb offical documentation, it says:

For example, the collection data has the following index:

{ a: 1, b: 1, c: 1, d: 1 }

The following operations can use the index to get the sort order:

Example

db.data.find( { a: 5 } ).sort( { b: 1, c: 1 } )

db.data.find( { b: 3, a: 4 } ).sort( { c: 1 } )

db.data.find( { a: 5, b: { $lt: 3} } ).sort( { b: 1 } )

I do not understand the second example, why query {b: 5, a: 4} with sort {c: 1} can use the index {a: 1, b: 1, c: 1, d: 1}.

Here is offical documentation.

Noam Hacker
  • 4,671
  • 7
  • 34
  • 55
王如锵
  • 941
  • 7
  • 17
  • 1
    Because you are actually specifying `"a"` and `"b"` which **do in fact prefix the index**. I think you are basically being confused thinking that since you ordered the keys in the query as `"b"` and then `"a"` that this means it's different, but it it not. If instead your query was `{ "c": 4, "b": 3 }` or `{ "b": 3, "c": 4 }` **then** you are not able to use the index because the compound starts with **"a"**. The order of keys in the **query** does not matter. It's only the "keys in the index" that matter. – Neil Lunn Aug 08 '17 at 04:16
  • Also to add what Neil has mentioned, to MongoDB query planner, `db.collection.find({b:5, a:4})` is identical to `db.collection.find({a:4, b:5})`. That is, the order of the keys in what is essentially an `$and` query does not matter. – kevinadi Aug 08 '17 at 05:43
  • Possible duplicate of [MongoDB : Indexes order and query order must match?](https://stackoverflow.com/questions/5245737/mongodb-indexes-order-and-query-order-must-match) – 王如锵 Aug 08 '17 at 06:05

0 Answers0