I'm creating a MongoDB aggregation pipeline and I'm stuck at this stage:
$group: {
_id: {checkType: "$_id.checkType", resultCode: "$_id.resultCode"},
count: { $sum: "$count" },
ctv: { $sum: "$ctv" },
perc:{$multiply:[{$divide:["$ctv","$count"]},100]},
weight: { $divide: [ "$ctv", "$count"] },
details: { $push: "$$ROOT" }
}
It gives the error "The $multiply accumulator is a unary operator". Similarly if I remove the line with $multiply I get "The $divide accumulator is a unary operator" on the subsequent line. I cannot find a description for this error on the Net. What's wrong in my sintax?
The arithmetic operators cannot be used as $group
accumulators. Move them to another $project
pipeline stage as:
db.collection.aggregate([
{ "$group": {
"_id": { "checkType": "$_id.checkType", "resultCode": "$_id.resultCode" },
"count": { "$sum": "$count" },
"ctv": { "$sum": "$ctv" },
"details": { "$push": "$$ROOT" }
} },
{ "$project": {
"count": 1,
"details": 1,
"ctv": 1,
"perc": { "$multiply": [ { "$divide": ["$ctv","$count"] }, 100 ] },
"weight": { "$divide": ["$ctv", "$count"] },
} }
])
or
if using MongoDB 3.4 and above, use $addFields
instead of $project
db.collection.aggregate([
{ "$group": {
"_id": { "checkType": "$_id.checkType", "resultCode": "$_id.resultCode" },
"count": { "$sum": "$count" },
"ctv": { "$sum": "$ctv" },
"details": { "$push": "$$ROOT" }
} },
{ "$addFields": {
"perc": { "$multiply": [ { "$divide": ["$ctv","$count"] }, 100 ] },
"weight": { "$divide": ["$ctv", "$count"] },
} }
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With