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

时间:2016-01-11 19:46:50

标签: node.js mongodb mongodb-query

假设我在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']},

我想从以下数组中找到包含TWO OR MORE的文档:['first', 'second', third', 'fourth', 'fifteenth']

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

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

这显然不是一个优雅的解决方案。还有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

您可以使用aggregate管道使用$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"] }}