简体   繁体   中英

MongoDB: Aggregation with arrays

I have some documents with a field as array:

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

And I want a group result as: (I need the sum of the values in position 0 of array, the sum of values in the position 1..) aggregated by player.

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

But i don't know how make it, some idea?

Use aggregation with $arrayElemAt to returns the element at the specified array index.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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