Targeted vs. Scatter Gather Queries

Hello.
Having more fields forming a shard key. I’d expected it forms a compound index and order matters to hit targeted query. Yet in the quiz, both answers are correct as if order does not matter.
What is correct?

Hi @Petr_Studeny,

First of all Congratulation on completing that course… :clap:

Yeah, having more fields forms the shard key which is either an indexed field or indexed compound fields that determine the distribution of the collection’s documents among the cluster’s shards.

And yes order matters in compound indexed fields, and the fields in the index need to be in a specific order but the fields in the find() query do not need to be in a specific order.

for example, if the index was: { "a" : 1, "b" : 1, "c": 1 }

all the following queries would be targeted :

db.products.find( { "a" : 250, "b": 1000, "c": 50 } )
db.products.find( { "a" : 250, "c": 50, "b": 1000 } )
db.products.find( { "c": 50, "a" : 250, "b": 1000 } )

these queries would also be targeted :

db.products.find( { "a" : 250, "b": 1000 } ).sort( { "c": 1 } )
db.products.find( { "b": 1000, "a" : 250 } ).sort( { "c": 1 } )

however, this query would not be targeted:

db.products.find( { "a" : 250, "c": 50 } ).sort( { "b": 1 } )

to summarize, the fields in the find() query can be rearranged to form an index prefix.

but once you filter results on a and c, like in the last example, you cannot use the same index to sort on b

So, here in the quiz the two queries are actually identical, and can both be targeted using the common shard key as fields are in the find() query.

So, the answer stated there to the quiz is correct.

I hope it clarifies your doubt.

If you still have any further questions feel free to reach out.

We wish you Happy Learning. :slightly_smiling_face:

Thanks
Kushagra

3 Likes

Thanks for response. Just to be super clear

db.products.find( { "a" : 250, "c": 50 } )

would not be targeted because index c can’t be used without b?

What about

db.products.find( { "a" : 250 } ).sort( { "c": 1 } )

I’d say the find itself is targeted and the sorting is made on mongos?

1 Like

Hi @Petr_Studeny,

Yes, you are correct. It wouldn’t be targeted.

The sorting is done on the primary shard.

You can read more about prefixes and query plan.

Edit 1:
You can also use explain() command to better understand how these queries are processing.
The explain command-tab is also available in MongoDB Compass. Feel free to explore it.

I hope it clarifies your doubt.
If you still have any questions feel free to reach out.

Regards,
Kushagra

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