
## Aggregate workgroups

`POST /v1/workgroups/aggregate`

Count of workgroups, numeric aggregates, and grouping by filter. Without a request body it returns the total number of workgroups in a single call, without fetching records.

**Standard fields:**

- `membersCount` — number of members (numeric aggregation is meaningful)
- `active` — activity flag (for `groupBy`)
- `isProject` — project flag (for `groupBy`)
- `ownerId` — workgroup owner (for `groupBy`)

## Request fields (body)

| Parameter | Type | Required | Description |
|----------|-----|:-----:|---------|
| `aggregate` | array | no | Array of aggregations. Numeric function: `{ "field": "membersCount", "function": "sum" }`. Count function: `{ "field": "*", "function": "count" }`. Functions: `count`, `sum`, `avg`, `min`, `max`. Without the array only `count` is returned |
| `filter` | object | no | Filtering by fields from `GET /v1/workgroups/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 |
| `groupOrderBy` | array | no | Group sorting: `[{ "field": "membersCount:sum", "direction": "desc" }]` |
| `groupLimit` | number | no | Limit on the number of groups returned (1-1000) |

The `sum`, `avg`, `min`, and `max` functions require a numeric field name, while `count` requires the `"*"` field. Numeric aggregation for workgroups is meaningful on the `membersCount` field — the number of members.

## Examples

### curl — personal key

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/workgroups/aggregate" \
  -H "X-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "aggregate": [
      { "field": "membersCount", "function": "sum" },
      { "field": "membersCount", "function": "avg" },
      { "field": "membersCount", "function": "min" },
      { "field": "membersCount", "function": "max" }
    ]
  }'
```

### curl — OAuth application

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/workgroups/aggregate" \
  -H "X-Api-Key: YOUR_APP_KEY" \
  -H "Authorization: Bearer USER_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "aggregate": [
      { "field": "membersCount", "function": "sum" },
      { "field": "membersCount", "function": "avg" },
      { "field": "membersCount", "function": "min" },
      { "field": "membersCount", "function": "max" }
    ]
  }'
```

### JavaScript — personal key

```javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/workgroups/aggregate', {
  method: 'POST',
  headers: {
    'X-Api-Key': 'YOUR_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    aggregate: [
      { field: 'membersCount', function: 'sum' },
      { field: 'membersCount', function: 'avg' },
      { field: 'membersCount', function: 'min' },
      { field: 'membersCount', function: 'max' },
    ],
  }),
})

const { success, data } = await res.json()
console.log('Total members across all workgroups:', data.aggregates.membersCount.sum)
```

### JavaScript — OAuth application

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

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

## Other scenarios

The total number of workgroups in the Bitrix24 account, the fastest request without fetching records:

```json
{}
```

Average workgroup size among projects:

```json
{
  "filter": { "isProject": true },
  "aggregate": [{ "field": "membersCount", "function": "avg" }]
}
```

Breakdown of the workgroup count by the activity flag:

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

## Response fields

| Field | Type | Description |
|------|-----|---------|
| `success` | boolean | Always `true` on success |
| `data.count` | number | Number of workgroups matching the filter |
| `data.aggregates` | object | Results of numeric aggregations by field. Empty object if the `aggregate` array is not passed |
| `data.groups` | array | Groups (only with `groupBy`). Each element: the grouping fields, `count`, and `aggregates` |
| `data.meta.totalRecords` | number | Total number of workgroups matching the filter |
| `data.meta.recordsProcessed` | number | How many records were processed: `0` for a plain `count`, the number of records for numeric functions and for `groupBy` |
| `data.meta.truncated` | boolean | `true` if more than 5000 records matched the filter and the result was computed over the first 5000. Always `false` for a plain `count` request |
| `data.meta.groupTotal` | number | Number of groups in the breakdown. Returned only with `groupBy` |
| `data.meta.groupsTruncated` | boolean | Indicates that some groups were omitted from the response. Returned only with `groupBy` |

## Response example

Numeric aggregates over the `membersCount` field:

```json
{
  "success": true,
  "data": {
    "count": 33,
    "aggregates": {
      "membersCount": {
        "sum": 65,
        "avg": 1.9696969696969697,
        "min": 0,
        "max": 7
      }
    },
    "meta": {
      "totalRecords": 33,
      "recordsProcessed": 33,
      "truncated": false
    }
  }
}
```

Grouping, body `{ "groupBy": "active" }`:

```json
{
  "success": true,
  "data": {
    "count": 33,
    "aggregates": {},
    "groups": [
      {
        "active": true,
        "count": 33,
        "aggregates": {}
      }
    ],
    "meta": {
      "totalRecords": 33,
      "recordsProcessed": 33,
      "truncated": false,
      "groupTotal": 1,
      "groupsTruncated": false
    }
  }
}
```

Count request, body `{}`, records are not fetched and `recordsProcessed` is `0`:

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

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

## Error response example

400 — the field passed in `groupBy` does not support grouping. The message contains the list of allowed fields:

```json
{
  "success": false,
  "error": {
    "code": "INVALID_PARAMS",
    "message": "groupBy field 'name' is not aggregatable on this entity. Available: membersCount, active, isProject, ownerId."
  }
}
```

## Errors

| HTTP | Code | Description |
|------|-----|---------|
| 400 | `INVALID_PARAMS` | Invalid function name, a numeric function on a non-numeric field, `groupBy` over a non-aggregatable field, or more than 5 fields in `groupBy` |
| 403 | `SCOPE_DENIED` | The API key lacks the `sonet_group` scope |
| 401 | `TOKEN_MISSING` | The API key has no configured tokens |

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

## Known specifics

**`count` vs numeric functions and grouping.** `count` is computed in a single call at any volume — records are not fetched, `recordsProcessed` is `0`, and the result matches the `total` field from the [workgroup list](./list.md). The `sum`, `avg`, `min`, `max` functions and grouping via `groupBy` fetch records page by page and are computed on the platform side, so `recordsProcessed` equals the number of processed workgroups. When more than 5000 records match the filter, `meta.truncated` becomes `true` and the result is computed over the first 5000 — for an exact result on large selections, narrow the filter.

## See also

- [List workgroups](/docs/entities/workgroups/list)
- [Search workgroups](/docs/entities/workgroups/search)
- [Filtering syntax](/docs/filtering)
