首页 > 解决方案 > $in 需要一个数组作为第二个参数

问题描述

我正在尝试进行一些聚合,但遇到以下问题。我需要使用“管道”,当我正在寻找的数组丢失时出现错误。

{
    $lookup: {
        from: 'comments',
        let: { comments: '$comments' },
        pipeline: [
            {
                $match: {
                    $expr: {
                        $in: ['$_id', '$$comments']
                    },
                    isDeleted: false
                }
            }
        ],
        as: 'comments'
    }
}

在这个阶段,我收到以下错误:

'$in requires an array as a second argument, found: missing'

因为并非所有文档都有“评论”字段。

注意:我使用的是管道而不是foreingFieldlocalField,因为我需要使用isDeleted: false可能还有其他匹配条件进行过滤。

仅当文档具有字段注释时才进行此查找吗?

谢谢!

标签: mongodbmongoosemongodb-queryaggregation-framework

解决方案


您可以在中添加$ifNull$and不为空或存在条件$expr

{
    $lookup: {
        from: 'comments',
        let: { comments: '$comments' },
        pipeline: [
            {
                $match: {
                    $expr: {$and: [
                        {$in: ['$_id', {$ifNull :['$$comments',[]]}]},
                        {$eq: ["$isDeleted", false]}
                    ]}
                }
            }
        ],
        as: 'comments'
    }
}

推荐阅读