Search code examples
arangodbaql

Query code for finding highest value of collections?


I'm new to arango, and want to find the highest value(located in a content object) from a group of collections, i have tried to use MAX but that didn't work.


Solution

  • You can use the following query with AGGREGATE, which is an efficient way of finding the highest value:

    FOR doc IN collection
      COLLECT AGGREGATE max = MAX(doc.value)
      RETURN max
    

    If you want to return the document with the highest value, then you can sort in descending order and return the first document:

    FOR doc IN collection
      SORT doc.value DESC
      LIMIT 1
      RETURN doc
    

    Note that there could be multiple documents with the same highest value unless there is an index on the field with a uniqueness constraint. If you want to return all documents with the highest value, then you can first determine the highest value in a sub-query, then filter by that value:

    LET max = FIRST(FOR doc IN collection COLLECT AGGREGATE max = MAX(doc.value) RETURN max)
    FOR doc IN collection
      FILTER doc.value == max
      RETURN doc