我有一些文档,其字段为数组:
{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}]}
但是我不知道怎么做,知道吗?
答案 0 :(得分:0)
与$arrayElemAt
一起使用聚合以返回指定数组索引处的元素。
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' }] } },
])