This is the action that replaces a loop. Fetching ten thousand orders to add up their amounts is ten thousand documents across the wire; the same question answered here is one row.
Parameters
collectionstringrequiredWhich collection the pipeline starts from.
pipelineJSON textrequiredA non-empty list of stages. Empty or absent is refused.
await storage.run({
action: "aggregate",
collection: "orders",
pipeline: JSON.stringify([
{ $match: { status: "paid", createdAt: { $gte: "2026-01-01" } } },
{ $group: { _id: "$country", total: { $sum: "$amount" }, orders: { $sum: 1 } } },
{ $sort: { total: -1 } },
{ $limit: 10 },
]),
});
// [{ _id: "FR", total: 184200, orders: 912 }, …]import json
storage.run(
action="aggregate",
collection="orders",
pipeline=json.dumps([
{"$match": {"status": "paid", "createdAt": {"$gte": "2026-01-01"}}},
{"$group": {"_id": "$country", "total": {"$sum": "$amount"}, "orders": {"$sum": 1}}},
{"$sort": {"total": -1}},
{"$limit": 10},
]),
)
# [{"_id": "FR", "total": 184200, "orders": 912}, …]Every stage name begins with $. Passed as a nested object through a caller that strips those keys, the pipeline arrives empty of its own stages and the call fails with nothing to explain it.
Two families of stage are refused
| Refused | Why |
|---|---|
| $where · $function · $accumulator | They execute code inside the database. |
| $out · $merge | They write the result into a collection — that is not a read. |
Both are caught before the pipeline is sent, so a refusal costs nothing and reaches nothing. To write a result, read it and insert it — which is a write, asked for as one.
The bounds
| Bound | Value |
|---|---|
| Results | 500 — put $limit in the pipeline so you choose which 500. |
| Time | 30 seconds. |
A pipeline that hits the time ceiling usually wants a $match first: filter, then group. Grouping everything and filtering afterwards does the expensive part on everything.