> To build or manage a Wix site with an AI agent, follow https://www.wix.com/headless/skill.md
> It builds a new Wix site or puts your own site online, from a prompt, and keeps changing it afterwards. The pages are code in any web technology, and Wix runs the backend.
> It works through the Wix plugin (the Wix MCP and the Wix skills), the Wix CLI or no Wix login, and puts the site live on Wix hosting or on another host.
> Business features include a store, bookings, events and tickets, a restaurant, a blog, forms, members and many more.
> Read the Wix skills online at https://www.wix.com/skills
> 
> Portal Navigation:
> 
> - Append `.md` to any URL under `https://dev.wix.com/docs/` to get its markdown version.
> - Pages are either content pages (article or reference text) or menu pages (a list of links to child pages).
> - To get a menu page, truncate any URL to a parent path and append `.md` (e.g. `https://dev.wix.com/docs/sdk.md`, `https://dev.wix.com/docs/sdk/core-modules.md`).
> - If a reference page seems to be missing its schema (parameters, return types, or type definitions), append `?schema=true` to its `.md` URL (e.g. `https://dev.wix.com/docs/contexts/contexts/stores/category-info/use-category-info-context.md?schema=true`).
> - Top-level index of all portals: https://dev.wix.com/docs/llms.txt
> - Full concatenated docs: https://dev.wix.com/docs/llms-full.txt

# AggregateDataItems

# Package: externalDatabases

# Namespace: ExternalDatabaseService

# Method link: https://dev.wix.com/docs/api-reference/business-solutions/cms/external-databases/external-database-service-plugin/aggregate-data-items.md

## Introduction

Runs an aggregation query on the specified data collection and returns the resulting list of items.

---

## REST API

### Schema

```
 Method: aggregateDataItems
 Description: Runs an aggregation query on the specified data collection and returns the resulting list of items.
 URL: {DEPLOYMENT-URI}/v3/items/aggregate
 Method: POST
 # Note: If the parameter `a.b` is listed under required parameters, `b` is only required if `a` is also present.
 Required parameters:  collectionId, consistentRead, returnTotalCount
 Method parameters: 
   param name: aggregation | type: Aggregation    
        - name: groupingFields | type: array<string> | description: Fields by which to group items for the aggregation, in the order they appear in the array. If empty, the aggregation must be applied to the entire collection.  
        - name: operations | type: array<Operation> | description: Operations to carry out on the data in each grouping.  
           - ONE-OF: 
              - name: average | type: Average | description: Calculate the average value of a specified field for all items in the grouping.  
                 - name: itemFieldName | type: string | description: Name of the field for which to calculate the average value.  
              - name: min | type: Min | description: Calculate the minimum value of a specified field for all items in the grouping.  
                 - name: itemFieldName | type: string | description: Name of the field for which to calculate the minimum value.  
              - name: max | type: Max | description: Calculate the maximum value of a specified field for all items in the grouping.  
                 - name: itemFieldName | type: string | description: Name of the field for which to calculate the maximum value.  
              - name: sum | type: Sum | description: Calculate the sum of values of a specified field for all items in the grouping.  
                 - name: itemFieldName | type: string | description: Name of the field for which to calculate the sum.  
              - name: itemCount | type: Count | description: Calculate the number of items in the grouping.  
       EMPTY-OBJECT {}
           - name: resultFieldName | type: string | description: Name of the field that contains the results of the operation.  
   param name: collectionId | type: collectionId | description: GUID of the collection on which to run the aggregation. | required: true 
   param name: consistentRead | type: consistentRead | description: Whether to retrieve data from the primary database instance. This decreases performance but ensures data retrieved is up-to-date even immediately after an update. Applicable if the external database is eventually consistent. | required: true 
   param name: finalFilter | type: finalFilter | description: Filter to apply to the processed data after aggregation. See [API Query Language](https://dev.wix.com/docs/rest/articles/getting-started/api-query-language.md#the-filter-section) for more information about handling data queries.  
   param name: initialFilter | type: initialFilter | description: Filter to apply to the collection's data before aggregation. See [API Query Language](https://dev.wix.com/docs/rest/articles/getting-started/api-query-language.md#the-filter-section) for more information about handling data queries.  
    - ONE-OF: 
     - name: paging | type: Paging | description:   
        - name: limit | type: integer | description: Number of items to load.  | validation: minimum 0, format int32
        - name: offset | type: integer | description: Number of items to skip in the current sort order.  | validation: minimum 0, format int32
     - name: cursorPaging | type: CursorPaging | description:   
        - name: limit | type: integer | description: Number of items to load.  | validation: minimum 0, maximum 1000, format int32
        - name: cursor | type: string | description: Pointer to the next or previous page in the list of results.  You can get the relevant cursor token from the `pagingMetadata` object in the previous call's response. Not relevant for the first request.  
   param name: returnTotalCount | type: returnTotalCount | description: When `true`, the query response must include the total number of items that match the query. | required: true 
   param name: sort | type: array<sort> | description: Sorting configuration.  
              - name: fieldName | type: string | description: Name of the field to sort by.  
              - name: order | type: SortOrder | description: Sort order.  
                     - enum: ASC, DESC
 Return type: AggregateDataItemsResponse
  - name: items | type: array | description: Aggregation results. Each result must contain a field for each `groupingFields` value, and a field for each `operations.resultFieldName` value.  
  - name: pagingMetadata | type: PagingMetadataV2 | description: Paging information.  
     - name: total | type: integer | description: Total number of items that match the query. Returned if offset paging is used and the `tooManyToCount` flag is not set.  | validation: format int32
     - name: cursors | type: Cursors | description: Cursors to navigate through the result pages using `next` and `prev`. Returned if cursor paging is used.  
        - name: next | type: string | description: Cursor pointing to next page in the list of results.  
        - name: prev | type: string | description: Cursor pointing to previous page in the list of results.  


```

### Examples

### Data aggregation request with two grouping fields
```curl
curl -X POST https://external-db.example.com/v3/items/aggregate  \
    -H 'Content-Type: application/json;charset=UTF-8' \
    -H 'Authorization: <AUTH>' \
    -d '{
  "collectionId": "cities",
  "aggregation": {
    "groupingFields": ["country", "isCapital"],
    "operations": [{
      "resultFieldName": "sumPopulation",
      "sum": {
        "itemFieldName": "population"
      }
    }]
  },
  "sort": [{
    "fieldName": "country",
    "order": "ASC"
  }, {
    "fieldName": "isCapital",
    "order": "ASC"
  }],
  "paging": {
    "limit": 50,
    "offset": 0
  },
  "consistentRead": false,
  "returnTotalCount": false
}'
```

### Data aggregation request with no grouping fields
```curl
curl -X POST https://external-db.example.com/v3/items/aggregate  \
    -H 'Content-Type: application/json;charset=UTF-8' \
    -H 'Authorization: <AUTH>' \
    -d '{
  "collectionId": "cities",
  "initialFilter": {
    "country": "US"
  },
  "aggregation": {
    "groupingFields": [],
    "operations": [{
      "resultFieldName": "sumPopulation",
      "sum": {
        "itemFieldName": "population"
      }
    }]
  },
  "sort": [],
  "paging": {
    "limit": 50,
    "offset": 0
  },
  "consistentRead": false,
  "returnTotalCount": false
}'
```

### Data aggregation request
Aggregation request with an initial filter, aggregation operations, and a final filter.

```curl
curl -X POST https://external-db.example.com/v3/items/aggregate  \
    -H 'Content-Type: application/json;charset=UTF-8' \
    -H 'Authorization: <AUTH>' \
    -d '{
  "collectionId": "cities",
  "initialFilter": {
    "isCapital": false
  },
  "aggregation": {
    "groupingFields": ["country"],
    "operations": [{
      "resultFieldName": "sumPopulation",
      "sum": {
        "itemFieldName": "population"
      }
    }, {
      "resultFieldName": "countOfCities",
      "itemCount": {
      }
    }]
  },
  "finalFilter": {
    "countOfCities": {
      "$gt": 5.0
    }
  },
  "sort": [{
    "fieldName": "sumPopulation",
    "order": "ASC"
  }],
  "paging": {
    "limit": 50,
    "offset": 0
  },
  "consistentRead": false,
  "returnTotalCount": true
}'
```

---

## JavaScript SDK

### Schema

```
 Method: wixClientAdmin.data.externalDatabase.aggregateDataItems(request, metadata)
 Description: Runs an aggregation query on the specified data collection and returns the resulting list of items.
 Method parameters:
   param name: request | type: AggregateDataItemsRequest    
    - ONE-OF: 
     - name: paging | type: Paging | description:   
        - name: limit | type: integer | description: Number of items to load.  | validation: minimum 0, format int32
        - name: offset | type: integer | description: Number of items to skip in the current sort order.  | validation: minimum 0, format int32
     - name: cursorPaging | type: CursorPaging | description:   
        - name: limit | type: integer | description: Number of items to load.  | validation: minimum 0, maximum 1000, format int32
        - name: cursor | type: string | description: Pointer to the next or previous page in the list of results.  You can get the relevant cursor token from the `pagingMetadata` object in the previous call's response. Not relevant for the first request.  
        - name: collectionId | type: string | description: GUID of the collection on which to run the aggregation.  
        - name: initialFilter | type: object | description: Filter to apply to the collection's data before aggregation. See [API Query Language](https://dev.wix.com/docs/rest/articles/getting-started/api-query-language.md#the-filter-section) for more information about handling data queries.  
        - name: aggregation | type: Aggregation | description: Aggregation to apply to the data.  
           - name: groupingFields | type: array<string> | description: Fields by which to group items for the aggregation, in the order they appear in the array. If empty, the aggregation must be applied to the entire collection.  
           - name: operations | type: array<Operation> | description: Operations to carry out on the data in each grouping.  
              - ONE-OF: 
                 - name: average | type: Average | description: Calculate the average value of a specified field for all items in the grouping.  
                    - name: itemFieldName | type: string | description: Name of the field for which to calculate the average value.  
                 - name: min | type: Min | description: Calculate the minimum value of a specified field for all items in the grouping.  
                    - name: itemFieldName | type: string | description: Name of the field for which to calculate the minimum value.  
                 - name: max | type: Max | description: Calculate the maximum value of a specified field for all items in the grouping.  
                    - name: itemFieldName | type: string | description: Name of the field for which to calculate the maximum value.  
                 - name: sum | type: Sum | description: Calculate the sum of values of a specified field for all items in the grouping.  
                    - name: itemFieldName | type: string | description: Name of the field for which to calculate the sum.  
              - name: resultFieldName | type: string | description: Name of the field that contains the results of the operation.  
        - name: finalFilter | type: object | description: Filter to apply to the processed data after aggregation. See [API Query Language](https://dev.wix.com/docs/rest/articles/getting-started/api-query-language.md#the-filter-section) for more information about handling data queries.  
        - name: sort | type: array<Sorting> | description: Sorting configuration.  
           - name: fieldName | type: string | description: Name of the field to sort by.  
           - name: order | type: SortOrder | description: Sort order.  
                 - enum: ASC, DESC
        - name: consistentRead | type: boolean | description: Whether to retrieve data from the primary database instance. This decreases performance but ensures data retrieved is up-to-date even immediately after an update. Applicable if the external database is eventually consistent.  
        - name: returnTotalCount | type: boolean | description: When `true`, the query response must include the total number of items that match the query.  
   param name: metadata | type: Context | description: this message is not directly used by any service, it exists to describe the expected parameters that SHOULD be provided to invoked Velo methods as part of open-platform. e.g. SPIs, event-handlers, etc.. NOTE: this context object MUST be provided as the last argument in each Velo method signature.  Example: ```typescript export function wixStores_onOrderCanceled({ event, metadata }: OrderCanceledEvent) { ... } ```  
        - name: requestId | type: string | description: A unique identifier of the request. You may print this GUID to your logs to help with future debugging and easier correlation with Wix's logs.  
        - name: currency | type: string | description: [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) 3-letter currency code.  | validation: format CURRENCY
        - name: identity | type: IdentificationData | description: An object that describes the identity that triggered this request.  
           - ONE-OF: 
              - name: anonymousVisitorId | type: string | description: GUID of a site visitor that has not logged in to the site.  | validation: format GUID
              - name: memberId | type: string | description: GUID of a site visitor that has logged in to the site.  | validation: format GUID
              - name: wixUserId | type: string | description: GUID of a Wix user (site owner, contributor, etc.).  | validation: format GUID
              - name: appId | type: string | description: GUID of an app.  | validation: format GUID
        - name: languages | type: array<string> | description: A string representing a language and region in the format of `"xx-XX"`. First 2 letters represent the language code according to ISO 639-1. This is followed by a dash "-", and then a by 2 capital letters representing the region according to ISO 3166-2. For example, `"en-US"`.  
        - name: instanceId | type: string | description: The service provider app's instance GUID.  | validation: format GUID
 Return type: PROMISE<AggregateDataItemsResponse>
  - name: items | type: array | description: Aggregation results. Each result must contain a field for each `groupingFields` value, and a field for each `operations.resultFieldName` value.  
  - name: pagingMetadata | type: PagingMetadataV2 | description: Paging information.  
     - name: total | type: integer | description: Total number of items that match the query. Returned if offset paging is used and the `tooManyToCount` flag is not set.  | validation: format int32
     - name: cursors | type: Cursors | description: Cursors to navigate through the result pages using `next` and `prev`. Returned if cursor paging is used.  
        - name: next | type: string | description: Cursor pointing to next page in the list of results.  
        - name: prev | type: string | description: Cursor pointing to previous page in the list of results.  


```

### Examples

### Example of `items` and `pagingMetadata` return values
```javascript
import { externalDatabase } from '@wix/data/service-plugins';

externalDatabase.provideHandlers({

  aggregateDataItems: async ( payload ) => {
    const {request, metadata} = payload;
        // Use the `request` and `metadata` received from Wix and
        // apply custom logic.
      return {
        // Return your response exactly as documented to integrate with Wix.
        // Return value example:
        items: [
          {
            country: "US",
            sumPopulation: 2000000.0,
            countOfCities: 25.0
          },
          {
            country: "CA",
            sumPopulation: 1000000.0,
            countOfCities: 10.0
          }
        ],
        pagingMetadata: {
          total: 2
        }
      }
    }
});

```

### aggregateDataItems (self-managed)
Self-managed SDK calls require you to [create a client](https://dev.wix.com/docs/sdk/articles/work-with-the-sdk/about-the-wix-client.md).

```javascript
import { createClient } from '@wix/sdk';
import { externalDatabase } from '@wix/data/service-plugins';
// Import the auth strategy for the relevant access type
// Import the relevant host module if needed

const myWixClient = createClient ({
  modules: { externalDatabase },
  // Include the auth strategy and host as relevant
});


async function aggregateDataItems(request,metadata) {
  const response = await myWixClient.externalDatabase.aggregateDataItems(request,metadata);
};
```

---