Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoError: Unrecognized expression $addFields while adding a new field to elements of an array

In a collection i have documents which one of their fields equal to an array ("categories") which contain another documents, in below code why i get following error: MongoError: Unrecognized expression '$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
            })
        }
    })
like image 466
ADeveloperFromEarth Avatar asked Feb 22 '26 01:02

ADeveloperFromEarth


1 Answers

$addFields is an aggregation stage you can not use it as an operator over there, If you wanted to add a field to each sub-doc in an array & recreate the array itself with updated sub-docs, then try below query :

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
        })
    }
})

Ref : $addFields, $mergeObjects

like image 153
whoami - fakeFaceTrueSoul Avatar answered Feb 24 '26 16:02

whoami - fakeFaceTrueSoul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!