Search code examples
mongodbmongodb-queryaggregation-frameworkmongodb-charts

MongoDB two $mulitply in one aggregation


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


Solution

  • 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"
              ]
            }
          }
        }
      }
    })