Search code examples
arangodbaql

arangodb AQL aggregate result and return object


I want to aggregate some ratings in AQL. The below query

FOR l IN locations
COLLECT rating = l.rating WITH COUNT INTO ratings
RETURN {[rating]: ratings}

returns and array of object:

[
  {
    "Good": 4639
  },
  {
    "Bad": 517
  },
  {
    "So so": 1017
  }
]

what I need is one object like:

[
  {
    "Good": 4639,
    "Bad": 517,
    "So so": 1017
  }
]

Solution

  • You can use MERGE(doc) to achieve the desired result:

    RETURN MERGE (
      FOR l IN locations
        COLLECT rating = l.rating WITH COUNT INTO ratings
        RETURN {[rating]: ratings}
    )
    

    Tested with my test collection (using prop2 rather than rating):

    [
      {
        "baz": 1,
        "other": 2
      }
    ]