I would like to query with a specified list of array elements such that documents returned can only contain the elements I pass, but need not contain all of them.
Given documents like:
{
name: "Article 1",
tags: ["Funny", "Rad"]
}
{
name: "Article 2",
tags: ["Cool", "Rad"]
}
{
name: "Article 3",
tags: ["Rad"]
}
Here are some example arrays and their respective results.
["Rad"]
should return Article 3["Rad", "Cool"]
should return Article 2 and Article 3["Funny", "Cool"]
should return nothing, since there are no articles with only one of those tags or bothI'm sure I can pull this off with $where
but I'd like to avoid that for obvious reasons.
Match an Array To specify equality condition on an array, use the query document { <field>: <value> } where <value> is the exact array to match, including the order of the elements.
Use $match With $eq to Find Matching Documents in an Array in MongoDB. Use $match With $all to Find Matching Documents in an Array in MongoDB.
The $pullAll operator removes all instances of the specified values from an existing array. Unlike the $pull operator that removes elements by specifying a query, $pullAll removes elements that match the listed values.
Filter MongoDB Array Element Using $Filter Operator This operator uses three variables: input – This represents the array that we want to extract. cond – This represents the set of conditions that must be met. as – This optional field contains a name for the variable that represent each element of the input array.
You can do this by combining multiple operators:
db.test.find({tags: {$not: {$elemMatch: {$nin: ['Rad', 'Cool']}}}})
The $elemMatch
with the $nin
is finding the docs where a single tags
element is neither 'Rad' nor 'Cool', and then the parent $not
inverts the match to return all the docs where that didn't match any elements.
However, this will also return docs where tags
is either missing or has no elements. To exclude those you need to add a qualifier that ensures tags
has at least one element:
db.test.find({
tags: {$not: {$elemMatch: {$nin: ['Rad', 'Cool']}}},
'tags.0': {$exists: true}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With