luiquao
luiquao

Reputation: 1114

mongodb sum of $push 'ed fields

I am trying to find $sum of each field I $push during the $group stage in my aggregation pipeline:

$group: {
  _id: "$seller",
  sales: {
    $push: {
       profit: {
          $multiply: [ 
             "$ratio", // some internal number 
             { $subtract: ["$revenue", "$cost"] } 
          ]
       }
    }
  },
  total: "find $SUM OF sales.profit"
}

which generates roughly the following response:

{
   _id: "XYZ",
   sales: [
     { profit: 100 },
     { profit: 200 },
     { profit: 300 },
   ]
}

What would be the best approach here?

Upvotes: 0

Views: 25

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59557

One solution is an additional stage:

db.collection.aggregate([
  {$group: {
  _id: "$seller",
  sales: {
    $push: {
       profit: {
          $multiply: [ 
             "$ratio", // some internal number 
             { $subtract: ["$revenue", "$cost"] } 
          ]
       }
    }
  },
  {
    $addFields: {
      total: { $sum: "$sales.profit" }
    }
  }
])

or with some redundancy:

  _id: "$seller",
  sales: {
    $push: {
       profit: {
          $multiply: [ 
             "$ratio", // some internal number 
             { $subtract: ["$revenue", "$cost"] } 
          ]
       }
    }
  },
  total: {
    $sum: {
       $multiply: [ 
          "$ratio", // some internal number 
          { $subtract: ["$revenue", "$cost"] } 
       ]
    }
  },

Upvotes: 1

Related Questions