0

I have a Collection that consists of objects, made from an integer/string as key/attribute and some value.

Like this:

results
-> '1' : 231.034
-> '2' : 3267.123
-> '3' : 235.23

When I write:

"""FOR u IN collection
RETURN u.results"""

I get them in a random order like this,

[{'3' : 235.23, '1' : 231.034, '2' : 3267.123}]

How do I sort them according to their attribute?

I tried:

"""FOR u IN collection
SORT ATTRIBUTES(u.results) ASC
RETURN u.results"""

As well as all other combinations I could come up with.

Master117
  • 660
  • 6
  • 21

1 Answers1

0

Key value object can't be really sorted, If you want to sort by the keys you can do something like:

Original Object:

{
  "results": {
    "3": 235.23,
    "2": 3267.123,
    "1": 231.034
  }
}

Query:

for u in @@collection
    let keys = ATTRIBUTES(u.results)
    //convert keys to sorted array
    let sortedKeys = (for key in keys
        sort key asc
        return key
    )

    //convert to key value tuples
    let sortedObject = (
        for key in sortedKeys
            return {[key] : u.results[key]}
    )

    //merge to single document, can also do with zip
    return {results : MERGE(sortedObject)}

Out:

[
  {
    "results": {
      "1": 231.034,
      "2": 3267.123,
      "3": 235.23
    }
  }
]
Daniel Krom
  • 9,751
  • 3
  • 43
  • 44