1

I would like to get a sum from an array of arrays, but so far I have not found any solution.

The arrays look like this, and I would like to get the sum of all array values [2] Arrays

So with this array I should get the sum value of 13317 + 4719. I tried using $sum but I don't know how to point to the index 2 when it's inside of another array - $median_sale_prices.2 doesn't work in this case.

0

1 Answer 1

1

You may need to flatten the array field first by using the $unwind operator, after which you can then use the $arrayElemAt operator as an expression within the $sum accumulator operator to sum just the array element in a $group pipeline step.

The concept can be best explained with the following example:

Populate test collection

db.test.insert([
    { 
        "x": [
            [1, 1, 1],
            [0, 1, 1],
            [1, 0, 1],
            [1, 1, 0],
            [1, 0, 1],
            [0, 1, 1]
        ]
    }
])

Run aggregation query

db.test.aggregate([
    { "$unwind": "$x" },
    {
        "$group": {
            "_id": null,
            "total": { 
                "$sum": { 
                    "$arrayElemAt": [ "$x", 2 ] 
                } 
            }
        }
    }
])

Sample Output

{
    "_id" : null,
    "total" : 5
}

Applying the above to your case becomes trivial.

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

2 Comments

One more thing, why isn't this possible $multiply: { parseInt($arrayElemAt: [ "$median_sale_prices", 1 ]), parseInt($arrayElemAt: [ "$median_sale_prices", 2 ]) }
It's simply not possible because it's not a valid aggregation framework operator.

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.