For Loops
A FOR loop evaluates its body once for each item produced by a source and collects the returned values into an array. It is the primary iteration construct in FQL.
The source is evaluated once. The body — including the final RETURN — is evaluated once per item, and the result is always an array.
Iterating a source
The value after IN is the source. It can be an array, a range, or any expression that yields a collection, including a variable, a function call, or a bind parameter.
The 1..5 range produces the integers from 1 to 5.
The counter variable
A second variable after the loop variable receives the zero-based position of each item.
If you only need the position, ignore the value with _.
Shaping results
Clauses placed between the source and the RETURN transform the stream of items. They take effect in the order they are written.
FILTER
FILTER keeps only the items for which a condition is true.
SORT
SORT reorders the items by one or more keys. Each key may be followed by ASC (the default) or DESC.
LIMIT
LIMIT count keeps the first count items. LIMIT offset, count skips offset items first, then keeps count.
COLLECT
COLLECT groups items by one or more keys. The result has one entry per distinct group, and the original loop variable is no longer in scope — only the group keys and anything you collect alongside them.
WITH COUNT INTO counts the members of each group.
AGGREGATE computes values across each group, such as COUNT, SUM, MIN, MAX, or AVERAGE.
Looping on a condition
Instead of iterating a source, a FOR loop can repeat while a condition holds. WHILE checks the condition before each pass; DO WHILE checks it after, so the body always runs at least once. An optional loop variable provides a zero-based counter.
Because DO WHILE runs the body before testing the condition, the loop below produces one item even though the condition is false from the start:
Loops as values
A FOR loop written on its own is the query’s output. Wrapped in parentheses, it becomes a value you can assign or nest. See Subquery Expressions.