
## Aggregate employees

`POST /v1/users/aggregate`

Count employees with filtering:

- **`count`** — works on any request (with or without a filter).
- **`groupBy`** — by standard fields from the aggregation list (`active`, `isAdmin`, `isOnline`, `departmentId`, `workPosition`, `personalGender`, `personalCity`) and by user (UF) fields of any type.
- **`sum` / `avg` / `min` / `max`** — only by numeric-type UF fields: `integer`, `double`, `money`.

## Request fields (body)

| Parameter | Type | Req. | Description |
|----------|-----|:-----:|---------|
| `aggregate` | array | no | Array of aggregations. Each element: `{ "field": "UF_*", "function": "sum" }`. For `count`, the field is `"*"`. Without the parameter — only `count` |
| `filter` | object | no | Filtering by `GET /v1/users/fields` fields.<br>[Filtering syntax](/docs/filtering). Accepts `camelCase` and `UPPER_SNAKE_CASE` |
| `groupBy` | string \| string[] | no | Field name or array (up to 5). Supported: standard fields `active`, `isAdmin`, `isOnline`, `departmentId`, `workPosition`, `personalGender`, `personalCity`; as well as any Bitrix24 account UF fields |

## Examples

### curl — personal key

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

### curl — OAuth application

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

### JavaScript — personal key

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

const { success, data } = await res.json()
console.log('Active employees:', data.count)
```

### JavaScript — OAuth application

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

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

> To group by several fields, pass an array: `"groupBy": ["active", "workPosition"]` (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" }] }
```

Distribution by activity status — how many employees are active, how many are deactivated:

```json
{ "groupBy": "active" }
```

Grouping by the "Internal number" UF field:

```json
{ "groupBy": "UF_PHONE_INNER" }
```

Sum over a numeric UF field with grouping:

```json
{
  "aggregate": [{ "field": "UF_SALARY", "function": "sum" }],
  "groupBy": "UF_DEPARTMENT"
}
```

## Response fields

| Field | Type | Description |
|------|-----|---------|
| `success` | boolean | Always `true` on success |
| `data.count` | number | Number of records matching the filter |
| `data.aggregates` | object | Aggregation results (empty object if the request had no `aggregate`) |
| `data.groups` | array | Groups (only with `groupBy`). Each element: grouping field values + `count` |
| `data.meta.totalRecords` | number | Total number of records matching the filter |
| `data.meta.recordsProcessed` | number | Number of processed records |
| `data.meta.truncated` | boolean | `true` if more than 5000 records matched and some did not make it into the selection |

## Response example

Response to a `count` request without `groupBy`:

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

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

## Error response example

400 — `groupBy` by a nonexistent field (the message contains the list of available standard and UF fields):

```json
{
  "success": false,
  "error": {
    "code": "INVALID_PARAMS",
    "message": "groupBy field 'nonexistent' is not aggregatable on this entity. Available: active, isAdmin, isOnline, departmentId, workPosition, personalGender, personalCity. User-defined: UF_DEPARTMENT (string), UF_PHONE_INNER (string), UF_EMPLOYMENT_DATE (string), UF_SKILLS (string), UF_INTERESTS (string), UF_LINKEDIN (string), UF_FACEBOOK (string)."
  }
}
```

## Errors

| HTTP | Code | Description |
|------|-----|---------|
| 400 | `INVALID_PARAMS` | Nonexistent or invalid field in `groupBy` or `aggregate.field` — the message contains the list of available fields |
| 400 | `INVALID_PARAMS` | A non-numeric-type UF field (`string`, `enumeration`, `date`) in `sum`/`avg`/`min`/`max` — the message names the type |
| 400 | `INVALID_PARAMS` | More than 5 fields in `groupBy` |
| 401 | `TOKEN_MISSING` | The API key has no configured tokens |
| 403 | `SCOPE_DENIED` | The API key lacks the `user` scope |

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

## Known specifics

**`count` vs numeric functions.** `count` is computed with a single Bitrix24 call at any volume. `sum`/`avg`/`min`/`max` load records page by page (maximum 5000) and compute on the Vibecode side. With more than 5000 records matching the filter — `meta.truncated: true`, aggregation over the first 5000. For an exact count on large selections — use `count` or narrow the filter.

**Money fields.** UF fields of type `money` are stored in the `"amount|currency"` format (`"50000|USD"`) — the aggregate extracts the numeric part automatically, you can sum without parsing.

## See also

- [List employees](/docs/entities/users/list) — fetching records with pagination
- [Employee fields](/docs/entities/users/fields) — UF fields arrive in the common list
- [Filtering syntax](/docs/filtering)
- [Limits and optimization](/docs/optimization)
