Skip to content

collect()

collect() returns a list containing the values returned by an expression. Using this function aggregates data by amalgamating multiple records or values into a single list.

collect() is an aggregation function. Like GROUP BY in SQL.

Examples

This example works like GROUP BY.

nebula> UNWIND [1, 2, 1] AS a RETURN a;
+---+
| a |
+---+
| 1 |
+---+
| 2 |
+---+
| 1 |
+---+
nebula> UNWIND [1, 2, 1] AS a RETURN collect(a);
+------------+
| COLLECT(a) |
+------------+
| [1, 2, 1]  |
+------------+
nebula> UNWIND [1, 2, 1] AS a RETURN a, collect(a), size(collect(a))
+---+------------+------------------+
| a | COLLECT(a) | size(COLLECT(a)) |
+---+------------+------------------+
| 2 | [2]        | 1                |
+---+------------+------------------+
| 1 | [1, 1]     | 2                |
+---+------------+------------------+

You can sort reversely, limit output rows to 3, and collect the output into a list.

nebula> UNWIND ["c", "b", "a", "d" ] AS p \
    WITH p AS q \
    ORDER BY q DESC LIMIT 3 \
    RETURN collect(q);
+-----------------+
| COLLECT(q)      |
+-----------------+
| ["d", "c", "b"] |
+-----------------+
nebula> WITH [1, 1, 2, 2] AS coll \
    UNWIND coll AS x \
    WITH DISTINCT x \
    RETURN collect(x) AS ss
+--------+
| ss     |
+--------+
| [1, 2] |
+--------+

This example aggregates all players' names by their ages.

nebula> MATCH (n:player) RETURN collect(n.age);
+---------------------------------------------------------------+
| COLLECT(n.age)                                                |
----------------------------------------------------------------+
| [32, 32, 34, 29, 41, 40, 33, 25, 40, 37, ...                  |
----------------------------------------------------------------+

nebula> MATCH (n:player) RETURN n.age AS age, collect(n.name);
+-----+--------------------------------------------------------------------------+
| 27  | ["Cory Joseph"]                                                          |
+-----+--------------------------------------------------------------------------+
| 28  | ["Damian Lillard", "Paul George", "Ricky Rubio"]                         |
+-----+--------------------------------------------------------------------------+
| 29  | ["Dejounte Murray", "James Harden", "Klay Thompson", "Jonathon Simmons"] |
+-----+--------------------------------------------------------------------------+
...

Last update: April 22, 2021
Back to top