匹配包含 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屋!