## Aggregate dictionary records

`POST /v1/statuses/aggregate`

`count` and numeric aggregations `sum`, `avg`, `min`, `max` over CRM dictionary records with a filter. The primary scenario is `count`: how many records are in a dictionary or match a filter.

## Standard fields

Numeric functions apply to numeric fields of a record:

| Field | Purpose |
|------|------------|
| `sort` | Sort order — `min` / `max` / `avg` give the range of weights |
| `id` | Record identifier |
| `categoryId` | Pipeline ID for dictionaries of the form `DEAL_STAGE_N` |

The fields `entityId`, `statusId`, `name`, `semantics` are categorical. Only `count` with a filter is available for them. `groupBy` grouping is not supported for dictionaries. CRM dictionaries have no user fields.

## Request fields (body)

| Parameter | Type | Required | Description |
|----------|-----|:-----:|---------|
| `aggregate` | array | no | Array of aggregations of the form `{ "field": "sort", "function": "min" }`. Functions: `sum`, `avg`, `min`, `max` — only over the fields `sort`, `id`, `categoryId`. Without this parameter, `count` of records matching the filter is returned |
| `filter` | object | no | Filtering by record fields. Exact match only. [Filtering syntax](/docs/filtering). Example: `{ "entityId": "DEAL_STAGE" }` |

## Examples

### curl — personal key

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/statuses/aggregate" \
  -H "X-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "filter": { "entityId": "DEAL_STAGE" }
  }'
```

### curl — OAuth application

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/statuses/aggregate" \
  -H "X-Api-Key: YOUR_APP_KEY" \
  -H "Authorization: Bearer USER_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "filter": { "entityId": "DEAL_STAGE" }
  }'
```

### JavaScript — personal key

```javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/statuses/aggregate', {
  method: 'POST',
  headers: {
    'X-Api-Key': 'YOUR_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    filter: { entityId: 'DEAL_STAGE' },
  }),
})

const { success, data } = await res.json()
console.log('Stages in the pipeline:', data.count)
```

### JavaScript — OAuth application

```javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/statuses/aggregate', {
  method: 'POST',
  headers: {
    'X-Api-Key': 'YOUR_APP_KEY',
    'Authorization': 'Bearer USER_SESSION_TOKEN',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    filter: { entityId: 'DEAL_STAGE' },
  }),
})

const { success, data } = await res.json()
```

## Other scenarios

Total number of records across all dictionaries — `count` without a filter:

```json
{}
```

Range and average sort value of pipeline stages — numeric functions over the `sort` field:

```json
{
  "aggregate": [
    { "field": "sort", "function": "min" },
    { "field": "sort", "function": "max" },
    { "field": "sort", "function": "avg" }
  ],
  "filter": { "entityId": "DEAL_STAGE" }
}
```

The response to such a request contains a filled `data.aggregates`:

```json
{
  "success": true,
  "data": {
    "count": 8,
    "aggregates": {
      "sort": { "min": 10, "max": 80, "avg": 45 }
    },
    "meta": { "totalRecords": 8, "recordsProcessed": 8, "truncated": false }
  }
}
```

## Response fields

| Field | Type | Description |
|------|-----|---------|
| `success` | boolean | Always `true` on success |
| `data.count` | number | Number of records matching the filter |
| `data.aggregates` | object | Results of numeric functions over fields. For `count` without functions — an empty object `{}` |
| `data.meta.totalRecords` | number | Total number of records under the filter |
| `data.meta.recordsProcessed` | number | How many records were loaded for the calculation. For `count` — `0`, for numeric functions — the number of records processed |
| `data.meta.truncated` | boolean | `true` if there are more than 5000 records and the calculation was performed over the first 5000 |

## Response example

```json
{
  "success": true,
  "data": {
    "count": 8,
    "aggregates": {},
    "meta": {
      "totalRecords": 8,
      "recordsProcessed": 0,
      "truncated": false
    }
  }
}
```

With numeric functions the `data.aggregates` field is filled — see “Other scenarios”.

## Error response example

400 — numeric function over a nonexistent field:

```json
{
  "success": false,
  "error": {
    "code": "INVALID_PARAMS",
    "message": "Field 'nope' not found. Available numeric fields: id, sort, categoryId."
  }
}
```

## Errors

| HTTP | Code | Description |
|------|-----|---------|
| 400 | `INVALID_PARAMS` | Unknown function — the message lists the allowed ones: `count`, `sum`, `avg`, `min`, `max` |
| 400 | `INVALID_PARAMS` | Nonexistent field in `aggregate` — the message lists the numeric fields: `id`, `sort`, `categoryId` |
| 400 | `INVALID_PARAMS` | Non-numeric field in `sum` / `avg` / `min` / `max` — the message names the field type |
| 400 | `INVALID_PARAMS` | `groupBy` passed — grouping is not available for dictionaries |
| 403 | `SCOPE_DENIED` | The API key does not have the `crm` scope |
| 401 | `TOKEN_MISSING` | No API key was passed |

Full list of errors — [Errors](/docs/errors).

## Known specifics

**`count` versus numeric functions.** `count` is computed with a single call to Bitrix24 at any volume, records are not downloaded — that is why `data.meta.recordsProcessed` equals `0`. The functions `sum` / `avg` / `min` / `max` load records page by page and compute on the Vibecode side. For a selection of more than 5000 records, `data.meta.truncated: true` is returned, and the result is calculated over the first 5000.

**Grouping is not available.** Dictionary fields are not part of the groupable set, so `groupBy` returns `400 INVALID_PARAMS`. To count records by dictionary type, call `count` with the filter `filter[entityId]` separately for each type.

## See also

- [List of dictionaries](./list.md)
- [Search dictionary records](./search.md)
- [Dictionary fields](./fields.md)
- [Filtering syntax](/docs/filtering)
- [Limits and optimization](/docs/optimization)
