Aggregations
COLLECT for grouping, AGGREGATE for computing SUM, AVG, COUNT, MIN, MAX and statistical functions.
Group & Aggregate
Use the COLLECT clause to group documents and perform aggregations like counting, summing, or averaging.
Basic Grouping
Group results by one or more fields to find distinct values.
FOR doc IN users
COLLECT city = doc.city
RETURN { city }
Counting Groups
Count the number of items in each group using WITH COUNT INTO.
FOR doc IN users
COLLECT city = doc.city
WITH COUNT INTO count
RETURN { city, count }
Aggregation Functions
Calculate aggregates using functions like SUM, AVG, MIN, MAX.
FOR s IN sales
COLLECT product = s.product
AGGREGATE
total = SUM(s.amount),
average = AVG(s.amount),
min_amt = MIN(s.amount),
max_amt = MAX(s.amount)
RETURN { product, total, average, min_amt, max_amt }
Collecting Lists
Use COLLECT_LIST to aggregate values from the group into an array.
FOR u IN users
COLLECT city = u.city
AGGREGATE userNames = COLLECT_LIST(u.name)
RETURN {
city,
userNames
}
Restricting Group Items with KEEP
With INTO groups, each group array normally stores every variable in
scope. Add KEEP v1, v2 to store only those
variables — smaller results, no leaked document bodies.
FOR u IN users
LET n = u.name
COLLECT city = u.city INTO g KEEP n
RETURN { city, names: g[*].n }
Without KEEP, each item of g would also carry u.
Every name listed must be a variable in scope at the COLLECT — an
unknown name is an error, not an empty group item.
COLLECT variable = expression [, ...]
[INTO groupVariable [KEEP var1, var2, ...]]
[WITH COUNT INTO countVariable]
[AGGREGATE variable = FUNC(expression) [, ...]]
Aggregation Functions
Basic Aggregations
Statistical Functions
Aggregation Example
FOR u IN users
LET amounts = (FOR o IN orders FILTER o.user == u._key RETURN o.amount)
RETURN {
user: u.name,
total: SUM(amounts),
avg: ROUND(AVG(amounts), 2),
count: COUNT(amounts),
median: MEDIAN(amounts),
stddev: ROUND(STDDEV(amounts), 2)
}