MongoDB:与数组聚合

MongoDB: Aggregation with arrays

我有一些文档的字段为数组:

{idPlayer: 1, result: [{shots: 4},{shots: 1},{shots: 6}]}
{idPlayer: 1, result: [{shots: 4},{shots: 2},{shots: 4}]}
{idPlayer: 1, result: [{shots: 4},{shots: 6},{shots: 2}]}
{idPlayer: 1, result: [{shots: 5},{shots: 1},{shots: 6}]}
{idPlayer: 1, result: [{shots: 7},{shots: 1},{shots: 8}]}
{idPlayer: 1, result: [{shots: 7},{shots: 2},{shots: 1}]}
{idPlayer: 1, result: [{shots: 2},{shots: 1},{shots: 2}]}
{idPlayer: 2, result: [{shots: 2},{shots: 1},{shots: 4}]}
{idPlayer: 2, result: [{shots: 9},{shots: 4},{shots: 3}]}
{idPlayer: 2, result: [{shots: 6},{shots: 2},{shots: 2}]}
{idPlayer: 3, result: [{shots: 5},{shots: 1},{shots: 2}]}
{idPlayer: 3, result: [{shots: 6},{shots: 2},{shots: 1}]}

我想要一个组结果:(我需要数组位置 0 中值的总和,位置 1 中值的总和..)由玩家聚合。

{idPlayer: 1, result: [{sumShots: 33},{sumShots: 14},{sumShots: 29}]}
{idPlayer: 2, result: [{sumShots: 17},{sumShots: 7}, {sumShots: 9}]}
{idPlayer: 3, result: [{sumShots: 11},{sumShots: 3}, {sumShots: 3}]}

但是我不知道怎么做,有什么想法吗?

使用聚合 $arrayElemAt 到 returns 指定数组索引处的元素。

db.getCollection('xxx').aggregate([
    { $project: { idPlayer: '$idPlayer', pos1: { $arrayElemAt: ["$result", 0] }, pos2: { $arrayElemAt: ["$result", 1] }, pos3: { $arrayElemAt: ["$result", 2] } } },
    { $group: { _id: '$idPlayer', sumShots1: { '$sum': '$pos1.shots' }, sumShots2: { '$sum': '$pos2.shots' }, sumShots3: { '$sum': '$pos3.shots' }, } },
    { $project: { _id: 0, idPlayer: '$_id', result: [{ 'sumShots': '$sumShots1' }, { sumShots: '$sumShots2' }, { sumShots: '$sumShots3' }] } },
])