Suppose I have a document like this:
{
tags: ['a', 'b']
}
I want to find all documents that have only the tag a. My current query criteria is:
{
tags: {
$size: 1,
$in: ['a']
}
}
Is there a way to query using an equal operator?
Although queries on array fields implicitly check array values, you can also match the entire array. Consider the following example, which has a mix of strings and arrays of strings in the
tagsfield:Querying for
"a"intagswill match any array that contains"a"alone or in part:Although not shown, if we had a
tagsfield that was simply"a"(not an array, but the string value), it would certainly be matched as well.Querying for
["a"]intagswill match the documents containing only"a"in theirtagsfield as well as anytagsarrays containing the value["a"](i.e. nested array):If you can safely assume your schema will only store strings in its
tagsarray, this query might be more desirable than storing the array size in a separate field and adding that to your query criteria (also a viable solution, as Matt mentioned).