在MongoDB中查找文档,该文档的数组字段是查询数组的子集 [英] Find Documents in MongoDB whose with an array field is a subset of a query array
问题描述
假设我插入了一组文档,每个文档都有一个array
字段.我想找到所有文档,使它们的array
字段是查询数组的子集.例如,如果我有以下文档,
Suppose I have a insert a set of documents each with an array
field. I would like to find all documents such that their array
field is a subset of a query array. For example, if I have the following documents,
collection.insert([
{
'name': 'one',
'array': ['a', 'b', 'c']
},
{
'name': 'two',
'array': ['b', 'c', 'd']
},
{
'name': 'three',
'array': ['b', 'c']
}
])
并且我查询collection.find({'array': {'$superset': ['a', 'b', 'c']})
,我希望看到文档one
和three
,因为['a', 'b', 'c']
和['b', 'c']
都是['a', 'b', 'c']
的子集.换句话说,我想做Mongo $all
查询的反函数,该查询选择所有文档,以便查询数组是文档array
字段的子集.这可能吗?如果可以,怎么办?
and I query collection.find({'array': {'$superset': ['a', 'b', 'c']})
, I would expect to see documents one
and three
as ['a', 'b', 'c']
and ['b', 'c']
are both subsets of ['a', 'b', 'c']
. In other words, I'd like to do the inverse of Mongo's $all
query, which selects all documents such that the query array is a subset of the document's array
field. Is this possible? and if so, how?
推荐答案
有一种简单的方法可以通过聚合框架或查找查询来实现.
There is a simple way to do this with aggregation framework or with a find query.
查找查询很简单,但是您必须使用$ elemMatch运算符:
Find query is simple, but you have to use $elemMatch operator:
> db.collection.find({array:{$not:{$elemMatch:{$nin:['a','b','c']}}}}, {_id:0,name:1})
请注意,这表明我们不希望匹配一个数组,该数组的元素(同时)不等于"a","b"或"c".我添加了一个投影,该投影仅返回结果文档的名称字段,该字段是可选的.
Note that this indicates that we want to not match an array which has an element which is (at the same time) not equal to 'a', 'b' or 'c'. I added a projection which only returns the name field of the resultant document which is optional.
这篇关于在MongoDB中查找文档,该文档的数组字段是查询数组的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!