1

I'm trying to count sum of all balances for every currency in database. I had to group it by currency but $sum was returning an exception. Any ideas how to fix it ?

exception: query failed: (Location40237) The $sum accumulator is a unary operator

    db.getCollection("people").aggregate([
    {
        $group: {
            _id: { currency:  "$credit.currency" },
            sumCur: { $sum: [ { $toDouble:  "$credit.balance" }]}

        }
    }
])

Sample of data model:

{ 
    "_id" : ObjectId("5ea970747cd4ac05869977ec"), 
    "sex" : "Male", 
    "first_name" : "Wayne", 
    "last_name" : "Fields", 
    "job" : "Speech Pathologist", 
    "email" : "[email protected]", 
    "location" : {
        "city" : "Oyo", 
        "address" : {
            "streetname" : "Beilfuss", 
            "streetnumber" : "860"
        }
    }, 
    "description" : "vulputate justo in blandit ultrices enim lorem ipsum dolor sit amet consectetuer adipiscing elit proin interdum mauris", 
    "height" : "152.38", 
    "weight" : "66.81", 
    "birth_date" : "1990-02-21T02:55:03Z", 
    "nationality" : "Nigeria", 
    "credit" : [
        {
            "type" : "switch", 
            "number" : "6759888939100098699", 
            "currency" : "COP", 
            "balance" : "5117.06"
        }
    ]
}

1 Answer 1

2

$sum expects a scalar, numeric value while you're passing an array. You need to use $unwind first since different array elements may also have different currencies:

db.collection.aggregate([
    { $unwind: "$credit" },
    {
        $group: {
            _id: {
                currency: "$credit.currency"
            },
            sumCur: {
                $sum: { $toDouble: "$credit.balance" }
            }
        }
    }
])

Mongo Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.