How to sum corresponding elements in array

hi, my data is like

{
cid: "A",
arr:[0,1,2,3]
},
{
cid: "A",
arr:[3,2,1]
},
{
cid: "C",
arr:[2,2,2,2]
}

what i expect is as below, every position in arr will sum together and place in the same position as before.

{
cid: "A",
arr:[3,3,3,3]
},
{
cid: "C",
arr:[2,2,2,2]
}

how can i archive this? Thanks in advanced.

Hello @Lin_YiSen, welcome to the forum!

This is an aggregation query which returns the required result. The query can be written in various ways, and this is just one way. Please refer the Aggregation Pipeline Quick Reference for the syntax and example usage of various aggregation stages and operators.

db.collection.aggregate([
{ 
  $unwind: { 
      path: "$arr", 
      includeArrayIndex: "ix" 
  } 
},
{ 
  $group: { 
      _id: { cid: "$cid", ix: "$ix" }, 
      arrs: { $push: "$arr" } 
  } 
},
{ 
  $sort: { "_id.cid": 1, "_id.ix": 1 } 
},
{ 
  $addFields: { 
      arrs: { $sum: "$arrs" } 
  } 
},
{ 
  $group: { 
      _id: "$_id.cid", 
      arr: { $push: "$arrs" } 
  } 
},
{ 
  $project: { 
      cid: "$_id", 
      arr: 1, 
      _id: 0 
  } 
}
])
1 Like

hi Prasad
Really thanks for your help. i think we should add below step to finish.

$group: { 
      _id: "$cid", 
      arr: { $push: "$arr" } 
  } 

Hello @Lin_YiSen, the query I had posted returns the following result:

{ "arr" : [ 3, 3, 3, 3 ], "cid" : "A" }
{ "arr" : [ 2, 2, 2, 2 ], "cid" : "C" }

That is the result your are looking for, I see:

1 Like

hi Prasad
yes, you are right, no need to add push. Appreciate your help.

Hello @Lin_YiSen, no problems :slight_smile: