A department store maintains a clothing collection:
{ "_id": 1, "item": "sweater", "sizes": [ "XS", "S", "L" ] }
{ "_id": 2, "item": "t-shirt", "sizes": [ "S", "M", "L" ] }
{ "_id": 3, "item": "vest", "sizes": [ "M", "L", "XL", "XXL" ] }
An employee runs:
db.clothing.find( { "sizes": "M" } )
Which index should improve performance for this query the MOST?
The query filters only on the sizes field, so the most direct supporting index is a single-field index on sizes. Because sizes contains arrays, MongoDB automatically treats the resulting index as a multikey index and creates index entries derived from the array elements. That allows the query { sizes: 'M' } to locate matching documents through the index rather than scanning every document in the collection. Option B indexes item, which is not part of the predicate and therefore does not help this query. Option C contains sizes, but _id is the leading key and the query provides no equality restriction on _id; this prevents efficient use of the later key as a standalone prefix for the query. Option D has the same structural problem because item precedes sizes and is not constrained. MongoDB's index-prefix rules make a targeted { sizes: 1 } index the strongest choice here. In a real workload, DBAs should also consider write overhead and whether additional queries can share a compound index before creating redundant indexes. For this single query pattern, option A is optimal.
Study Guide reference/topic:Indexing and Query Optimization - multikey indexes, array fields, index prefixes, and query support.
===========
Currently there are no comments in this discussion, be the first to comment!