sum of two int arrays in an aggregation query grouped by another field

If you have fixes size of two values then you can use this one:

db.collection.aggregate([
   { $group: { _id: null, data: { $push: "$d" } } },
   {
      $set: {
         d: [
            {$sum:{ $map: { input: "$data", in: { $first: "$$this" } } }},
            {$sum:{ $map: { input: "$data", in: { $last: "$$this" } } }}
         ]
      }
   },
   {$unset: "data"}
])

For any length use this one:

db.collection.aggregate([
   { $group: { _id: null, data: { $push: "$d" } } },
   {
      $set: {
         d: {
            $map: {
               input: { $range: [0, { $size: { $first: "$data" } }] },
               as: "idx",
               in: { $sum: { $map: { input: "$data", in: { $arrayElemAt: ["$$this", "$$idx"] } } } }
            }
         }
      }
   }
])

The first array determines the length of all the other arrays.

Another approach is this one:

db.collection.aggregate([
  { $unwind: { path: "$d", includeArrayIndex: "idx" } },
  { $group: { _id: "$idx", d: { $sum: "$d" } } },
  { $sort: { _id: 1 } },
  { $group: { _id: null, d: { $push: "$d" } } }
])

Or if you like to add other fields:

db.collection.aggregate([
  { $unwind: { path: "$d", includeArrayIndex: "idx" } },
  { $group: { _id: "$idx", d: { $sum: "$d" }, date: { $first: "$date" } } },
  { $sort: { _id: 1 } },
  { $group: { _id: "$date", d: { $push: "$d" } } },
  { $project: { d: 1, date: "$_id" } }
])

This works even if the arrays do not all have the same length.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top