Can queries have the compounded Shard Keys in a different order?

Excerpt from course

Example of a compound shard key:

{ "sku": 1, "type": 1, "name": 1 }

Examples of queries that would be **targeted** with the compound shard key:

db.products.find( { "sku": ... } ) 
db.products.find( { "sku": ... , "type": ... } ) 
db.products.find( { "sku": ... , "type": ... , "name": ... } )

Examples of queries that would be **scatter-gather** with the compound shard key:

db.products.find( { "type": ... } ) 
db.products.find( { "name": ... } )

Here what I need to understand is whether the following are valid “targetted” queries

  • db.products.find( { "sku": ... , "type": ... , "name": ... } )
  • db.products.find( { "name": ... , "sku": ... , "type": ... } )
  • db.products.find( { "type": ... , "name": ... , "sku": ... } )

Or does the order of shard keys matter?

Never mind, I figured that the order doesn’t matter…

Hi @Shrinidhi_Rao ,

Your observation is correct: a query to a sharded collection just has to include all of the fields in a compound shard key index (in any order) to target the shards that may contain matching documents.

In the more general case, the order of keys in a query does not have to match the order of keys in a compound index definition. However, the order and direction of keys in a compound index definition is definitely important and should follow guidelines like the ESR (Equality, Sort, Range) Rule.

You can explain query results to confirm which indexes are used and which shards are accessed for a query.

Regards,
Stennie

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.