I have a collection where I only ever need to look up documents by whole arrays; I can’t think of any scenario where I’d want to look up documents by just one value of that array. Unfortunately, the multikey feature that is always activated for array values apparently can’t be deactivated.
In the documentation it says “The index will be used to lookup a subset of the values (currently the first one) and then the document will be inspected for the exact match.” I think this greatly decreases the performance in my case. Despite the index some lookups take 70 ms and some several minutes, because, depending on the first element, MongoDB sometimes has to search through a few thousand or several hundred thousand documents. At least that is my theory.
Is there some way to avoid this problem, or should I rather serialize my arrays and store them as strings?
Thanks in advance!
Perhaps you could use a subdocument like:
So that you can do matches like:
update I discovered what caused the failure for large arrays. Index keys > 800 bytes will not be indexed. So, if you have a large subdocument and you put an index on it, if it's greater than 800 bytes, and you try to search for it, you won't find it. If you take the index off and search again for the same subdocument, you'll find it (although it will be a full collection scan).
This is documented here as a limitation, and will be removed in future releases: https://jira.mongodb.org/browse/SERVER-3372
So, this will work in general for small arrays.
Here's some test code in case anyone wants to try it out: