Chapter 4 - Covered Queries Quiz

Hey there,
I was looking to the quiz answers, and I have a question about one of the rules that I can’t apply for a covered query:

- You Can’t Cover a query if any of the indexed field are arrays

With this, the “correct” answer isn’t so correct?
db.example.find( { name : { $in : [ "Bart", "Homer" ] } }, {_id : 0, dob : 1, name : 1} )

Clearly, the name field is an array.
Maybe I didn’t understand the concept after all.

No it is not. You may apply $in to a simple value field.

1 Like

Hi @Maykel_Esser and welcome to the MongoDB Community forums! :wave:

As Steeve states, you can use $in to compare against any type of value. I think you might be getting confused in that you must pass an array of values to the $in operator. Each item passed in the array here will be compared against each document.

You can learn more about covered queries in the documentation. In that documentation you will see the following:

Multikey indexes cannot cover queries over array field(s).

The above should help clear things up for you. If not, let us know.

3 Likes

@steevej and @Doug_Duncan! Thanks for reply!
I knew that I can apply $in operator in any kind of value. But, the lesson argument is very clear: u can’t cover a query if the indexed field is an array.

I thought: if the expression $in compares with an array, I can’t use the advantages of covered queries.
Because of that, I still don’t get it. Even if I use $in with or without an array, the answer should be wrong, just because the value proposed was, in fact, an array.

Or, is just about the multikey indexes, that I can’t apply those concepts?

The $in operator requires an array of values. You cannot use the operator without using an array. If you try to use anything other than an array it will throw an error:

image

This has no relation to the field being checked. name could contain fields of any data type.

A multikey index could be used if the index was created that contained a field that was an array, as long as that field was not the name field. In this case it could be covering index (depending on other circumstances). The note I posted above says that the multikey index can not cover a query over the array fields.

If it would help, I can provide some examples later on with notes around what’s going on.
If’ I’m misunderstanding what you’re trying to ask let me know.

1 Like