Run an Aggregation Pipeline

This guide explains how to build and run an aggregation pipeline. The aggregation pipeline lets you perform complex transformations and calculations on data items. A pipeline consists of 1 or more stages that process your data sequentially, with each stage's output becoming the input for the next stage.

The pipeline allows you to:

  • Group items and calculate aggregate values.
  • Transform result items by including, excluding, or reshaping fields.
  • Filter, sort, and limit results.

Note: You can only build an aggregation pipeline for collections created in the CMS or with the Data Collections API. You can't use them on Wix app collections or external collections.

Anatomy of a pipeline

An aggregation pipeline has the following key components:

  • aggregatePipeline(): Runs an aggregation pipeline on the specified collection and returns the results.
  • pipelineBuilder(): Builds an aggregation pipeline with stages and pagination configuration.
  • Stages: Operations that process and transform data sequentially. Each stage type performs a different operation.
  • Expressions: Operators and values for performing calculations, transformations, and field manipulations.

Build and run an aggregation pipeline

Building and running an aggregation pipeline involves 2 main phases: building the pipeline with your desired stages, then running it on a collection:

  1. Import the items module and deconstruct the required submodules:

    Copy
  2. Add 1 or more stages to build the pipeline:

    Copy

    Some stages resolve expressions to perform calculations and transformations. For example, you can create a new field by combining existing fields:

    Copy
  3. Pass the stages array to the withStages() method. You can also add paging configuration with the withPaging() method. Finally, call build() to build the pipeline:

    Copy

    The pipeline is now ready.

  4. Pass the configured pipeline to the aggregatePipeline() method to run the pipeline on the collection:

    Copy

See also

Did this help?