【问题标题】:How can I query mongo to find arrays that contain TWO elements from another array如何查询 mongodb 以查找包含来自另一个数组的两个元素的数组
【发布时间】:2016-01-12 04:36:27
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: node.js mongodb mongodb-query


    【解决方案1】:

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

    【讨论】:

    • 哇太棒了!我从未听说过 $setIntersection
    猜你喜欢
    • 2022-01-02
    • 2013-10-11
    • 2021-12-30
    • 2014-05-02
    • 2022-01-09
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多