'Getting sum value in Dataweave

I need to get the total price of the order in Dataweave.

<?xml version='1.0' encoding='UTF-8'?>
<Orders>
  <Order id="10001">
    <ProductId id="P001">P-001</ProductId>
    <ProductName>Samsung 40Inch TV</ProductName>
    <Category id="C001">Samsung TV</Category>
    <Price>399</Price>
    <Quantity>5</Quantity>
  </Order>
  <Order id="10001">
    <ProductId id="P002">P-002</ProductId>
    <ProductName>Samsung 32Inch TV</ProductName>
    <Category id="C001">Samsung TV</Category>
    <Price>299</Price>
    <Quantity>5</Quantity>
  </Order>
</Orders>

I've tried the following dataweave without success:

%dw 2.0
output application/json
---
{
 "totalCost": sum(payload.Orders.*Order.Price)  
}


Solution 1:[1]

the below code will generate total price of each order

%dw 2.0
output application/json
---
payload.Orders.*Order map(
    "totalCost": $.Price * $.Quantity
)

output:-

[
  {
    "totalCost": 1995
  },
  {
    "totalCost": 1495
  }
]

if you want total cost for all the orders then use below script

%dw 2.0
output application/json
---
"totalCost" : sum(payload.Orders.*Order map(
    $.Price * $.Quantity
))

output:-

{
  "totalCost": 3490
}

Solution 2:[2]

The script seems to be doing what it is expected, ie sum all the Prices in Orders. Since it is not clear in the question I will guess that you need to calculate instead the 'total cost' of an order, assuming it is its price multiplied by quantity. For that you have to first map each Order to its price * quantity, before calculating the sum:

%dw 2.0
output application/json
---
{
    "totalCost": sum(payload.Orders.*Order map ($.Price * $.Quantity))
}

Output:

{
  "totalCost": 3490
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sandeep Sai Kumar
Solution 2 aled