Final Exam - Question 6

Hi everyone,

One of the good answers to this question seems wrong to me:

She seems to be saying that this is the only way to get a Multikey index. But there are also nested document insertion, no ?

Hi @grolip,

You’re right, but I think that you haven’t understand the answer in the good way.

In fact, you can have an index like this :
{name: 1, emails:1}

If all your documents looks like this :
{
“name” : “John”,
“emails”: “john@hotmail.com
}

so your index is not multikey.

Now suppose that you insert a new document like this :
{
“name” : “Lisa”,
“emails”: [
lisa@hotmail.com”,
lisa@gmail.com
]
}

The field “emails” contains an array now, so your index just becomed a multikey index, because at least one field of your index is an array.

The course says :

So MongoDB only recognizes that an index is multikey when a document is inserted where that field is in an array.

I hope I have been helpful :slight_smile:

Thx for answer,

The same happens if emails field contains a nested document. Right ?
The answer should have been:

Or

Note: I translate the answers into French, maybe there was a loss of meaning.

But maybe just wait for another student’s answer to be sure, as it is important to have a good comprehension of this course.

@grolip,

In fact I had a doubt.

So I’ve watched the lesson again, and I think my previous answer was wrong. I’m sorry.

The teacher says :

when we index on a field that is an array, this is what we call a multikey index.

I did a test with Compass and the explain plan show that a index key become multikey when a field become an array.

In the course, the teacher talks about nested document just to say that you can index them with a multikey.

So the answer would be the second, I think it’s correct this time.

Have a lovely day.

2 Likes

Indeed, I am completely wrong.

To index a field that holds an array value, MongoDB creates an index key for each element in the array. These multikey indexes support efficient queries against array fields. Multikey indexes can be constructed over arrays that hold both scalar values [1] (e.g. strings, numbers) and nested documents.

Nested document… in array !!
misunderstanding + mistranslation !

Thank you for your insight.