## Aggregate dictionary records

`POST /v1/statuses/aggregate`

Count (`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` | Funnel 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. Grouping via `groupBy` 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, the `count` of records matching the filter is returned |
| `filter` | object | no | Filtering by record fields — `id`, `entityId`, `statusId`, `name`, `sort`, `semantics`, `categoryId`. Only exact equality on a single value. A list of values (`$in` or an array) is not supported on any field — such a filter is rejected with `400 UNSUPPORTED_FILTER`. Count each value with a separate call, or combine the calls in [`POST /v1/batch`](/docs/batch).<br>[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 funnel:', 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 funnel 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 populated `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 matching 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` when the numbers were computed over only some of the records that match the filter: fewer records were read than `data.count` promised — including when more than 5000 matched the filter — or the slice was cut short by a sub-page error. The size of the gap is reported in `data.meta.recordsShortfall`, the interrupted slice in `data.meta.pageErrorSample`. Always present, and `false` on a complete response. If the request has neither `groupBy` nor a numeric function, no records are fetched and the flag is always `false` |

## Response example

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

With numeric functions, the `data.aggregates` field is populated — 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 |
| 400 | `UNSUPPORTED_FILTER` | A list of values — `$in` or an array — was passed in `filter`. The message names the field and lists the filterable ones: `id`, `entityId`, `statusId`, `name`, `sort`, `semantics`, `categoryId` |
| 403 | `SCOPE_DENIED` | The API key does not have the `crm` scope |
| 401 | `MISSING_API_KEY` | The `X-Api-Key` header is missing |
| 429 | `RATE_LIMITED` | Rate limit exceeded: 300 requests per minute per portal. All API keys of the portal share one limit. The current limit is returned in the `x-ratelimit-limit` header. Retry after the delay in the `Retry-After` header |

For the full list of errors, see [Errors](/docs/errors).

## Known specifics

**`count` versus numeric functions.** `count` is computed with a single call to Bitrix24 regardless of volume and does not download records — 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. If more than 5000 records match the filter, `data.meta.truncated: true` is returned and the result is calculated over the first 5000. The ceiling is not the only reason for this marker: it also appears when fewer records were read than `data.count` promised, and the size of the gap is reported in `data.meta.recordsShortfall`.

**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.

**The truncation marker travels with the number itself.** When a response arrives with `meta.truncated: true`, the marker `truncated: true` sits inside every field object in `data.aggregates` and on every element of `data.groups`, and `data.meta.warnings` gains a warning with the code `AGGREGATE_TRUNCATED`. A client that reads only the number itself therefore sees that it was computed over only some of the records. None of these markers appear on a complete response. Full details — [Aggregation POST — the 5000-record ceiling](/docs/entity-api#aggregation-post-the-5000-record-ceiling).

## 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)
