匹配包含MongoDB中提供的数组的任意组合的数组字段 [英] Matching an array field which contains any combination of the provided array in MongoDB
问题描述
我想查询指定的数组元素列表,以便返回的文档只能包含我传递的元素,而不必包含所有元素.
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.
给出如下文件:
{
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"]
应返回第3条 -
["Rad", "Cool"]
应返回第2条和第3条 -
["Funny", "Cool"]
应该不返回任何内容,因为没有文章中只有一个或两个标签
["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 both
我敢肯定我可以用$where
做到这一点,但是出于明显的原因,我想避免这种情况.
I'm sure I can pull this off with $where
but I'd like to avoid that for obvious reasons.
推荐答案
您可以通过组合多个运算符来做到这一点:
You can do this by combining multiple operators:
db.test.find({tags: {$not: {$elemMatch: {$nin: ['Rad', 'Cool']}}}})
带有$nin
的$elemMatch
正在查找单个tags
元素既不是'Rad'也不是'Cool'的文档,然后父级$not
将该匹配取反以返回所有文档,其中没有任何元素.
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.
但是,这也会返回缺少tags
或没有元素的文档.要排除那些元素,您需要添加一个限定符,以确保tags
具有至少一个元素:
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}
})
这篇关于匹配包含MongoDB中提供的数组的任意组合的数组字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!