# aggregate

Canonical URL: https://developers.iagenify.com/sdk/ref/connected-storage/run/aggregate/
Language: en

`storage.run({ action: "aggregate", collection, pipeline })`

Group, join, compute — in the database, and bring back the answer instead of the rows.

Status: document database · free · 500 results · 30 s

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 {#parameters}

| Name | Type | Requirement | Description |
| --- | --- | --- | --- |
| `collection` | string | required | Which collection the pipeline starts from. |
| `pipeline` | JSON text | required | A non-empty list of stages. Empty or absent is refused. |

```javascript
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 }, …]
```

> **The pipeline is JSON text, and this is where it matters most**
>
> 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}

| 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](/sdk/ref/connected-storage/run-write/insert) it — which is a write, asked for as one.

## The bounds {#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.

- [find](/sdk/ref/connected-storage/run/find): Quand ce sont les documents qu'on veut.
- [run()](/sdk/ref/connected-storage/run): Toutes les actions, les garde-fous et ce que chacune coûte.

```python
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}, …]
```
