MongoDB two $mulitply in one aggregation

26 Views Asked by At

Hi I would like to seek help if how can I achieve that the total will be multiplied by 0.20 and will be named transaction.

This is my current aggregation. See Playground

1

There are 1 best solutions below

1
Someone Special On BEST ANSWER

Why not just add a transaction field?

db.collection.aggregate({
  $addFields: {
    "products": {
      $map: {
        input: "$products",
        as: "p",
        in: {
          "$mergeObjects": [
            {
              total: {
                $multiply: [
                  "$$p.price",
                  "$$p.quantity"
                ]
              },
              transactions: {
                $multiply: [
                  "$$p.price",
                  "$$p.quantity",
                  0.2
                ]
              }
            },
            "$$p"
          ]
        }
      }
    }
  }
})