我如何查询mongo来查找包含另一个数组的TWO元素的数组

假设我在mongo中有以下文件:

{_id: 0, tags: ['first', 'second', 'third', fourth']}, {_id: 1, tags: ['fifth', 'seventh', 'first', second']}, {_id: 2, tags: ['eigth', 'awesometh', 'fancyth']}, {_id: 3, tags: ['fourth', 'fifteenth', 'something']}, 

我想从以下数组中find包含两个或两个以上的文档: ['first', 'second', third', 'fourth', 'fifteenth']

我到目前为止唯一的想法是用每个组合的子句生成I巨大的查询,如下所示:

 {$or: [ {tags: {$in: ['first', 'second']}}, {tags: {$in: ['second', 'third']}}, {tags: {$in: ['first', 'third']}}, ...etc... ] } 

这显然不是一个优雅的解决scheme。 有没有更好的办法?

您可以使用$setIntersection来查找匹配的tags ,然后使用$size来计算它们:

 var tags = ['first', 'second', 'third', 'fourth', 'fifteenth']; db.test.aggregate([ // Project the original doc along with a count of the tag matches {$project: { _id: 0, matches: {$size: {$setIntersection: ['$tags', tags]}}, doc: '$$ROOT' }}, // Filter to just those docs with at least 2 matches {$match: {matches: {$gte: 2}}} ]) 

产量

 { "matches": 4, "doc": { "_id": 0, "tags": ["first", "second", "third", "fourth"] }} { "matches": 2, "doc": { "_id": 1, "tags": ["fifth", "seventh", "first", "second"] }} { "matches": 2, "doc": { "_id": 3, "tags": ["fourth", "fifteenth", "something"] }}