Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: error with $divide and $multiply

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?

like image 428
Pino Avatar asked Apr 11 '17 09:04

Pino


1 Answers

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"] },
    } }
])
like image 110
chridam Avatar answered Oct 13 '22 22:10

chridam