2
votes

I would like to know how to sort a collection in mule using Dataweave orderBy with multiple number of fields and also with ascending or descending order.

3

3 Answers

3
votes

Here is the sample code(with example) that I created to demonstrate multiple orderby and sorting. Note:- By default, the order by is ascending order and to achieve the descending order, just reverse the result at the end by [-1..0].

%dw 1.0
%var inputPayload=[
    {"name":"john",
      "age": "12"
    },
    {"name":"john3",
      "age": "15"
    },
    {"name":"john3",
      "age": "14"
    },
    {"name":"john1",
      "age": "13"
    },
    {"name":"john2",
      "age": "14"
    },

    {"name":"john5",
      "age": "17"
    }

]


%output application/json
---
((inputPayload orderBy $.name) orderBy $.age)[-1..0]

Output Payload - [ { "name": "john5", "age": "17" }, { "name": "john3", "age": "15" }, { "name": "john3", "age": "14" }, { "name": "john2", "age": "14" }, { "name": "john1", "age": "13" }, { "name": "john", "age": "12" } ]

2
votes

You have to use the OrderBy and concatenate operator for this. Giving an example below

payload orderBy ($.name ++ $.id)

0
votes

I think the accepted answer just re-orders the entire array twice and only works for that particular example. If you use an example where the age a number instead of a string like so

{
  "input": [
    {
      "name": "john",
      "age": 12
    },
    {
      "name": "john5",
      "age": 7
    },
    {
      "name": "john3",
      "age": 15
    },
    {
      "name": "john3",
      "age": 14
    },
    {
      "name": "john1",
      "age": 13
    },
    {
      "name": "john2",
      "age": 14
    }
  ]
}

then the output ends up in the wrong order for a multi-layer orderBy (it's the order you would expect if we just did orderBy age)

[
  {
    "name": "john3",
    "age": 15
  },
  {
    "name": "john3",
    "age": 14
  },
  {
    "name": "john2",
    "age": 14
  },
  {
    "name": "john1",
    "age": 13
  },
  {
    "name": "john",
    "age": 12
  },
  {
    "name": "john5",
    "age": 7
  }
]

whereas something like flatten(((inputPayload orderBy $.name) groupBy $.name) pluck ($ orderBy $.age))[-1..0] gives

[
  {
    "name": "john5",
    "age": 7
  },
  {
    "name": "john3",
    "age": 15
  },
  {
    "name": "john3",
    "age": 14
  },
  {
    "name": "john2",
    "age": 14
  },
  {
    "name": "john1",
    "age": 13
  },
  {
    "name": "john",
    "age": 12
  }
]

so the overall orderBy is name and then within the same name the orderBy is age