surrealdb

Aggregating into lists


Say whe have the following animals:

INSERT INTO animal (id, species, age)
  VALUES ("titi", "cat", 3), ("mimi", "cat", 4), ("kiki", "dog", 5);

Is there a simple way to select the animals grouped by their species?

[
    {
        species: 'cat',
        members: [
          { id: animal:mimi, age: 4 },
          { id: animal:titi, age: 3 }
        ],
    },
    {
        species: 'dog',
        members: [
          { id: animal:kiki, age: 5 }
        ],
    }
]

Here is what I tried:

1 | SELECT species, array::group({id, age}) AS members FROM animal GROUP BY species;
  |                              ^ expected this delimiter to close

Thanks!


Solution

  • Your initial approach is almost there, it needs a key added in the object to yield the desired result:

    SELECT species, array::group({id: id, age: age}) AS members FROM animal GROUP BY species;