Reputation: 108
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
})
}
})
Upvotes: 3
Views: 8584
Reputation: 17915
$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
Upvotes: 5