繁体   English   中英

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一起使用以返回指定数组索引处的元素。

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' }] } },
])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM