There are two potential interpretations of your question, so let me provide some clarification to help you get started.
First and foremost, it's important to note that your usage of the $elemMatch
operator is incorrect in this scenario.
The purpose of $elemMatch
is to create a "query document" that is applied to individual elements within an array, rather than to the entire array itself. For example:
{
"data": [
{ "a": 1, "b": 3 },
{ "a": 2, "b": 2 }
]
}
In this case, the query below will yield results because even though no single element in the array matches both conditions, the document as a whole does:
db.collection.find({ "data.a": 1, "data.b": 2 })
To check if a specific element meets both conditions, you should use $elemMatch
:
db.collection.find({ "data": { "a": 1, "b": 2 } })
This means that only elements with both attributes matching will be considered a match.
With that explanation of $elemMatch
out of the way, here's a simplified version of your query:
db.collection.find({ "tracks.artist": { "$in": arr } })
This query looks at each array member by a single field and returns documents where any element contains at least one of the specified values.
However, if you're looking for an "and" operation where all three values must be present, you can try using $all
:
db.collection.find({ "tracks.artist": { "$all": arr } })
This will only return documents where all elements match the specified values. If you need more complex operations, consider leveraging the aggregation framework.
If you're using MongoDB 2.6 or later, you have access to powerful operators like $setIntersection
and $map
. However, for older versions, you may need to resort to more intricate aggregation pipelines.