MongoDB的:聚合,数组

问题描述 投票:0回答:1

我有一个字段作为阵列的一些文件:

{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}]}

我想的一组结果为:(I需要在阵列的位置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}]}

但我不知道该怎么做了,有些想法?

arrays mongodb aggregation
1个回答
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' }] } },
])
© www.soinside.com 2019 - 2024. All rights reserved.