MongoError:向数组元素添加新字段时无法识别表达式 $addFields

ADe*_*rth 3 mongodb node.js mongodb-query aggregation-framework

在一个集合中,我有一些文档,其中一个字段等于一个数组(“类别”),其中包含另一个文档,在下面的代码中为什么我收到以下错误:MongoError:无法识别的表达式 '$addFields'

dbUsers.aggregate([
        {
            $match: {
                key: req.cookies.key
            }
        }, {
            $project: {
                categories: {
                    $map: {
                        input: {
                            $filter: {
                                input: '$categories',
                                as: 'category',
                                cond: { $eq: ['$$category.parentId', req.headers.parentid] }
                            }
                        },
                        as: 'current',
                        in: {
                            $addFields: {
                                countOfIntelligence: {
                                    $size: '$$current.listOfIntelligences'
                                }
                        }}
                    }
                }
            }
        }
    ]).toArray((err, res2) => {
        if (err) {
            console.log(err)
        } else {
            res.send({
                categories: res2
            })
        }
    })
Run Code Online (Sandbox Code Playgroud)

sri*_*asy 5

$addFields是一个聚合阶段,您不能将它用作那里的运算符,如果您想向数组中的每个子文档添加一个字段并使用更新的子文档重新创建数组本身,请尝试以下查询:

dbUsers.aggregate([
    {
        $match: {
            key: req.cookies.key
        }
    }, {
        $project: {
            categories: {
                $map: {
                    input: {
                        $filter: {
                            input: '$categories',
                            as: 'category',
                            cond: { $eq: ['$$category.parentId', req.headers.parentid] }
                        }
                    },
                    as: 'current',
                    in: {
                        $mergeObjects: ['$$current', {
                            countOfIntelligence: {
                                $size: '$$current.listOfIntelligences'
                            }
                        }]
                    }
                }
            }
        }
    }
]).toArray((err, res2) => {
    if (err) {
        console.log(err)
    } else {
        res.send({
            categories: res2
        })
    }
})
Run Code Online (Sandbox Code Playgroud)

参考: $addFields$mergeObjects