【问题标题】:How to stop second $lookup to run on the first one's output?如何停止第二个 $lookup 在第一个输出上运行?
【发布时间】:2022-01-26 23:32:44
【问题描述】:

所以我正在做这个项目,我有一个帖子集合,其中包含类别和作者等字段。我需要借助 MongoDB 的聚合来获取基于特定类别和作者的数据。

现在在我的聚合对象中,我有两个 $lookups 一个接一个,第二个查找是从第一个输出中过滤数据。因此,我没有从集合中获取与第二个查找条件匹配的所有数据。

假设在我的收藏中有 10 个类别和 10 个作者。首先,我需要获取所有类别名称为“X”的帖子(集合有 5 个 X)。所以在第一次查找时,它应该返回 5 个带有 X 的帖子。

因此,我还需要以同样的方式获取作者为“Y”的帖子(集合有 8 个 Y)。但现在它只返回 5 个 X 的所有 Y。但是我需要返回集合中与 Y 匹配的所有帖子,即其中 8 个。

这是聚合的 obj:

const aggregateObj = [ 
        {
            '$lookup': {
                'from': 'categories', 
                'localField': 'categories.category', 
                'foreignField': '_id', 
                'as': 'categories'
            }
        }, 
        {
            '$match': {
                "categories.category": {
                    $in: [ 'X' ]
                }
            }
        },
        {
            '$lookup': {
                'from': 'authors', 
                'localField': 'author', 
                'foreignField': '_id', 
                'as': 'author'
            }
        }, 
        {
            '$match': {
                "author.author": {
                    $in: [ 'Y' ]
                }
            }
        }
    ];

    const result = await Post
        .aggregate( aggregateObj )
        .exec();    

【问题讨论】:

    标签: node.js mongodb express mongoose aggregation-framework


    【解决方案1】:

    我认为这可能符合您的需要

    const aggregateObj = [ 
            {
                '$lookup': {
                    'from': 'categories', 
                    'localField': 'categories.category', 
                    'foreignField': '_id', 
                    'as': 'categories'
                }
            }, 
            {
                '$lookup': {
                    'from': 'authors', 
                    'localField': 'author', 
                    'foreignField': '_id', 
                    'as': 'author'
                }
            }, 
            {
                '$match': {
                    $or: [
                       {
                          "categories.category": {
                             $in: [ 'X' ]
                          }
                       },
                       {
                          "author.author": {
                              $in: [ 'Y' ]
                          }                 
                       }
                    ]
                }
            }
        ];
    

    【讨论】:

      猜你喜欢
      • 2012-07-12
      • 2020-04-14
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多