Given a MongoDB collection products with documents like:
{ "_id": 1, "tags": ["red", "cotton", "sale"] }and a multikey index on tags, what documents will this query return?
db.products.find({ tags: "cotton" })db.products.insertMany([
{ _id: 1, tags: ["red", "cotton", "sale"] },
{ _id: 2, tags: ["blue", "wool"] },
{ _id: 3, tags: ["cotton", "new"] }
])
db.products.createIndex({ tags: 1 })
db.products.find({ tags: "cotton" })Think about how multikey indexes work with array fields and matching values.
The multikey index indexes each element of the array separately. So the query matches documents where the tags array contains "cotton". Documents 1 and 3 have "cotton" in their tags, so they are returned.
Which of the following is a limitation of MongoDB multikey indexes on array fields?
Think about how MongoDB handles arrays inside arrays for indexing.
MongoDB multikey indexes do not support indexing nested arrays (arrays inside arrays). This is a known limitation. Other options are incorrect because MongoDB indexes all elements, does not require sorting, and has no strict 100 element limit.
Which of the following commands correctly creates a multikey index on the categories array field in MongoDB?
Remember how MongoDB creates indexes on fields, including arrays.
MongoDB automatically creates a multikey index when you create a normal index on an array field. The syntax is the same as for any field: { categories: 1 }. Other options are invalid syntax or unsupported.
Consider a collection with documents having two array fields: colors and sizes. You want to efficiently query documents where colors contains "red" and sizes contains "large".
Which index strategy is best for this query?
Think about how compound multikey indexes work with multiple array fields.
MongoDB supports compound multikey indexes on multiple array fields, which can optimize queries filtering on both fields. Separate indexes may cause inefficient query plans. Text and hashed indexes are not suitable for this type of query.
You created a multikey index on the tags array field. But this query is slow and does not use the index:
db.products.find({ tags: { $all: ["cotton", "sale"] } })What is the most likely reason?
Consider how MongoDB uses multikey indexes with $all operator.
Multikey indexes support $all queries, but when $all has multiple elements, MongoDB may not efficiently use the index if the array elements are large or the index is not selective enough. This can cause slow queries despite the index existing.