← All articles
DataWeave · MuleSoft · Quick Reads

Practical DataWeave groupBy Patterns

groupBy is useful when a flat collection needs to become a map of related records.

Given:

[
  {"orderId":"O1","region":"US","amount":20},
  {"orderId":"O2","region":"EU","amount":15},
  {"orderId":"O3","region":"US","amount":30}
]

Group by region:

%dw 2.0
output application/json
---
payload groupBy ((item) -> item.region)

Conceptually the result becomes:

{
  "US": [
    {"orderId":"O1","region":"US","amount":20},
    {"orderId":"O3","region":"US","amount":30}
  ],
  "EU": [
    {"orderId":"O2","region":"EU","amount":15}
  ]
}

Group, Then Aggregate

A common pattern is to group first and then transform each group.

%dw 2.0
output application/json
var grouped = payload groupBy ((item) -> item.region)
---
grouped mapObject ((records, region) -> {
  (region): {
    count: sizeOf(records),
    total: sum(records.amount)
  }
})

This is useful for summaries, regional batches and downstream request construction.

Group for Routing

Grouping can also prepare records for different destinations:

US records -> US endpoint
EU records -> EU endpoint
APAC records -> APAC endpoint

Keep transformation and routing responsibilities clear. DataWeave can shape the groups, while the Mule flow decides how those groups are processed.

Watch Cardinality

Grouping a large payload by a nearly unique key can create a very large object with many tiny arrays. Before using groupBy, ask whether the grouping materially reduces or organizes the dataset.

Final Principle

Use groupBy when the next processing step thinks in groups, not individual records. Grouping is most valuable when it simplifies a later aggregation, routing or batching decision.