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
}
COLLECT variable = expression [, ...]
[INTO groupVariable]
[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)
}