Search code examples
foreachmulemule-esb

ForEach Aggregation


I am using For-Each Processor. As a part of this i need to aggregate the responses of each iteration. For doing this i am using the below expression:

Step 1: Create a flowVar with name 'aggregator' with value '#[[]]'. This is initialised before For-Each Step2: In For-Each Processor once the processing is done. I use the following expression to aggregate: '#[flowVars.aggregation.add(message.payload)]'.

The Payload i get in each iteration is

[{
"Transactions": [
  {
    "Id": "",
    "CompanyId": "123",
    "ContractId": "777"
  },
  {
    "Id": "",
    "CompanyId": "123",
    "ContractId": "777"
  }
]

The result of aggregation is :

[{  
"Transactions": [
{
  "Id": "",
  "CompanyId": "123",
  "ContractId": "777"
},
{
  "Id": "",
  "CompanyId": "123",
  "ContractId": "777"
}
]
}, {
"Transactions": [
{
  "Id": "",
  "CompanyId": "555",
  "ContractId": "2345"
},
{
  "Id": "",
  "CompanyId": "7777",
  "ContractId": "2389"
}
  ]
}]

I want to merge data in single "Transactions" as a JSON Output. I am unable to achieve this.


Solution

  • Keeping with your current approach you could add the below dataweave after the aggregation:

    %dw 1.0
    %output application/json
    ---
    {
        Transactions: flatten payload.Transactions
    }
    

    If the input to this transform is the output of your aggregation that you described in your question, the output is:

    {
      "Transactions": [
        {
          "Id": "",
          "CompanyId": "123",
          "ContractId": "777"
        },
        {
          "Id": "",
          "CompanyId": "123",
          "ContractId": "777"
        },
        {
          "Id": "",
          "CompanyId": "555",
          "ContractId": "2345"
        },
        {
          "Id": "",
          "CompanyId": "7777",
          "ContractId": "2389"
        }
      ]
    }