I have a MongoDB collection with documents containing an array of subdocuments. For example:
{
"_id": 1,
"addresses": [
{ "city": "New York", "country": "USA" },
{ "city": "Toronto", "country": "Canada" }
]
}
I want to create an index on addresses.city but only for subdocuments where country is "USA".
I tried using a partial index like this:
db.users.createIndex(
{ "addresses.city": 1 },
{ partialFilterExpression: { "addresses.country": "USA" } }
)
However, I’m not sure how MongoDB handles this:
Will it index only the addresses elements where country is "USA"?
Or will it index all addresses.city values in the document if any element matches the partial filter?
I’m looking for clarification on how partial multikey indexes work with arrays of subdocuments. If MongoDB cannot index only matching subdocuments, are there any recommended workarounds?
MongoDB version: 7.0+ (but any explanation about multikey + partial indexes is helpful)