Aggregate queries

Aggregate queries in GraphQL are useful for summarizing data in various ways. They help in performing operations such as counting the number of records, summing up numerical fields, and grouping data based on specific fields.

Count Query

The count query allows you to count the number of records that match a specific condition.

query {
  countModelName(where: { fieldName: "value" }) {
    count
  }
}

Example:

query {
  countUsers(where: { status: "active" }) {
    count
  }
}

In this example, the query counts the number of users who have an active status.


Sum Query

The sum query allows you to sum the values of a specific numerical field across all records that match a given condition.

query {
  sumModelName(where: { fieldName: "value" }) {
    sumFieldName
  }
}

Example:

query {
  sumOrders(where: { status: "completed" }) {
    sumTotalAmount
  }
}

In this example, the query sums up the totalAmount of all orders that have a completed status.


Group By Query

The groupBy query allows you to group records by a specific field and perform aggregate functions like count or sum within each group.

query {
  groupByModelName(by: [fieldName], where: { fieldName: "value" }) {
    fieldName
    aggregateField {
      count
      sum
      ...otherAggregates
    }
  }
}

Example:

query {
  groupByProducts(by: ["category"]) {
    category
    aggregate {
      count
      sumPrice
    }
  }
}

This query groups products by their category and provides the count and sum of the price within each category.

Last updated