Kristjan Kirpu
Kristjan Kirpu

Reputation: 682

Mongo sum array index

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.

Upvotes: 1

Views: 1417

Answers (1)

chridam
chridam

Reputation: 103365

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.

Upvotes: 1

Related Questions