
## Aggregate companies

`POST /v1/companies/aggregate`

Count, sum, average, minimum and maximum over companies with filtering and grouping.

**Standard fields:**

- `revenue` — annual revenue (numeric aggregation makes sense)
- `typeId` — company type (for `groupBy`)
- `industry` — industry (for `groupBy`)
- `assignedById` — assigned person (for `groupBy`)
- `sourceId` — source (for `groupBy`)

**User fields (UF):** UF fields of type `integer`, `double`, `money` — for numeric functions; UF of any type — for `groupBy`. The full list of UF fields for a specific Bitrix24 account is returned in the `INVALID_PARAMS` error text if you pass a non-existent name.

## Request fields (body)

| Parameter | Type | Req. | Description |
|----------|-----|:-----:|---------|
| `aggregate` | array | no | Array of aggregations. Each element: `{ "field": "revenue", "function": "sum" }`. Functions: `count`, `sum`, `avg`, `min`, `max`. For `count`, the field is `"*"`. Without the array — only `count` |
| `filter` | object | no | Filter by `GET /v1/companies/fields` fields. [Filtering syntax](/docs/filtering) |
| `groupBy` | string \| string[] | no | Field or array of fields to group by (maximum 5). Allowed values — from the list above |

## Examples

### curl — personal key

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/companies/aggregate" \
  -H "X-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "aggregate": [
      { "field": "revenue", "function": "sum" },
      { "field": "revenue", "function": "avg" }
    ],
    "filter": { "typeId": "CUSTOMER" },
    "groupBy": "industry"
  }'
```

### curl — OAuth application

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/companies/aggregate" \
  -H "X-Api-Key: YOUR_APP_KEY" \
  -H "Authorization: Bearer USER_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "aggregate": [
      { "field": "revenue", "function": "sum" },
      { "field": "revenue", "function": "avg" }
    ],
    "filter": { "typeId": "CUSTOMER" },
    "groupBy": "industry"
  }'
```

### JavaScript — personal key

```javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/companies/aggregate', {
  method: 'POST',
  headers: {
    'X-Api-Key': 'YOUR_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    aggregate: [
      { field: 'revenue', function: 'sum' },
      { field: 'revenue', function: 'avg' },
    ],
    filter: { typeId: 'CUSTOMER' },
    groupBy: 'industry',
  }),
})

const { success, data } = await res.json()
console.log('Total companies:', data.count)
console.log('By industry:', data.groups)
```

### JavaScript — OAuth application

```javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/companies/aggregate', {
  method: 'POST',
  headers: {
    'X-Api-Key': 'YOUR_APP_KEY',
    'Authorization': 'Bearer USER_SESSION_TOKEN',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    aggregate: [
      { field: 'revenue', function: 'sum' },
      { field: 'revenue', function: 'avg' },
    ],
    filter: { typeId: 'CUSTOMER' },
    groupBy: 'industry',
  }),
})

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

> To group by several fields, pass an array: `"groupBy": ["industry", "typeId"]` (maximum 5).

## Other scenarios

Count records — `count` with field `"*"`, the fastest request without fetching records. Without the `aggregate` array the result is the same:

```json
{ "aggregate": [{ "field": "*", "function": "count" }] }
```

Working with user fields (UF) — `sum` over a UF + grouping by another UF:

```json
{
  "aggregate": [{ "field": "UF_CRM_BUDGET", "function": "sum" }],
  "groupBy": "UF_CRM_SEGMENT"
}
```

## Response fields

| Field | Type | Description |
|------|-----|---------|
| `success` | boolean | Always `true` on success |
| `data.count` | number | Total number of records matching the filter |
| `data.aggregates` | object | Aggregation results: `{ "revenue": { "sum": 3000000, "avg": 50000 } }` |
| `data.groups` | array | Groups (only with `groupBy`). Each element: grouping fields + `count` + `aggregates` |
| `data.meta.totalRecords` | number | Total number of records matching the filter |
| `data.meta.recordsProcessed` | number | How many records were processed for numeric aggregations (maximum 5000) |
| `data.meta.truncated` | boolean | `true` if more than 5000 records matched the filter |

## Response example

Response to the main request (aggregations + `groupBy: "industry"`):

```json
{
  "success": true,
  "data": {
    "count": 60,
    "aggregates": {
      "revenue": { "sum": 3000000, "avg": 50000 }
    },
    "groups": [
      {
        "industry": "IT",
        "count": 35,
        "aggregates": { "revenue": { "sum": 2000000 } }
      },
      {
        "industry": "RETAIL",
        "count": 25,
        "aggregates": { "revenue": { "sum": 1000000 } }
      }
    ],
    "meta": {
      "totalRecords": 60,
      "recordsProcessed": 60,
      "truncated": false
    }
  }
}
```

Without `groupBy`, the `data.groups` field is absent from the response.

## Error response example

400 — invalid function name, non-existent field, or `groupBy` on a non-aggregatable field:

```json
{
  "success": false,
  "error": {
    "code": "INVALID_PARAMS",
    "message": "Field 'foo' not found. Available numeric fields: typeId, industry, revenue, assignedById, sourceId"
  }
}
```

## Errors

| HTTP | Code | Description |
|------|-----|---------|
| 400 | `INVALID_PARAMS` | Invalid function name, non-existent field, non-numeric field in `sum`/`avg`/`min`/`max`, `groupBy` on a non-aggregatable field, or more than 5 fields in `groupBy` |
| 401 | `TOKEN_MISSING` | The API key has no configured tokens |
| 403 | `SCOPE_DENIED` | The API key does not have the `crm` scope |

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

## Known specifics

**`count` vs numeric functions.** `count` is computed as a single call to Bitrix24 regardless of data volume. The `sum`/`avg`/`min`/`max` functions fetch records page by page (maximum 5000) and compute on the Vibecode side — if more than 5000 records match the filter, `meta.truncated` will be `true` and the aggregation runs over the first 5000. For exact counts on large selections, use `count` or narrow the filter.

**Money fields.** UF fields of type `money` are stored in the format `"amount|currency"` (`"1500|USD"`) — the aggregate extracts the numeric part automatically, so values can be summed without parsing.

**Filtering by UF works.** In `filter` you can pass any fields — standard and user, of any type. For example, `{ "filter": { "ufCrm_1234": "value" } }` returns the number of companies with that UF value.

## See also

- [List companies](/docs/entities/companies/list) — get records with filtering
- [Search companies](/docs/entities/companies/search) — POST request with filters
- [Filtering syntax](/docs/filtering)
- [Limits and optimization](/docs/optimization) — rate limits
