Chapter 4 - Covered queries

Can someone explain for the quiz why the answer is the following:

db.example.find( { name : { $in : [ “Bart”, “Homer” ] } }, {_id : 0, dob : 1, name : 1} )

Based on the following indexes that are created:

{ _id: 1 }
{ name: 1, dob: 1 }
{ hair: 1, name: 1 }

Shouldn’t the answer be the following:

db.example.find( { name : { $in : [ “Bart”, “Homer” ] } }, {_id : 0, hair : 1, name : 1} )

Based on the definition of a covered query (all fields in the query are a part of the index and all the fields are turned in the result are in the same index.)

In order to clarify, the first question is, which index did it use?

Hi @steperez,

This will be the correct answer because name field in the query filter and both dob and name field in projection will use { name:1, dob: 1} index.

This query will again use { name:1, dob: 1} index as it is the only index covering name field first. This query will be thus the wrong choice as it will not be a covered query.

Please let me know if you have any questions.

Thanks,
Sonali

4 Likes

I too have the doubt . can you explain little more, In the video explanation , for a covered query , index values should be present in the projection values . As you say do we need to consider the position of index values too?

Hi @Lifas_Kassim,

I would recommend you to go through the following documentation link:

Please feel free to reach out if you have any additional questions.

Kind Regards,
Sonali

The documentation could be clearer. It says:

"- all the fields in the query are part of an index, and

  • all the fields returned are in the same index…"

Maybe the last line should say: “all the fields returned are in that same index”. How it is currently written suggests that two indexes could be used.

Hey @Keith_O_Dulaigh,

You can share any feedback related to the MongoDB documentation on the same page itself.

In the documentation, you will see the “Was this page helpful?” option:

Click on No and then you can share your feedback in the pop-up as below:
Screenshot 2021-01-07 at 5.47.31 PM

Please feel free to reach out if you have any questions.

Kind Regards,
Sonali

…maybe add a reminder about index prefix. I saw hair/name in the projection and name in the index, but forgot name in the query will use the index name/dob (prefix).