dehaze

Aggregations

You can easily perform aggregations on any table/collection using the aggregate field a table/collection. The allowed aggregation functions are count, min, max, avg, sum. For more advanced use cases, you can use prepared queries. You can also group, filter, sort data in the aggregations.

Note: Aggregations are only available in SQL databases as of now.

Simple aggregation query

Example: Fetch aggregated data of expenditures of a particular user:

query {
  expenditures(where: {user_id: "1"}) @postgres {
    aggregate {
      count {
        id
      }
      min {
        amount
      }
      max {
        amount
      }
      sum {
        amount
      }
      avg {
        amount
      }
    }
  }
}
const { status, data } = db.get("expenditures")
    .aggregateCount("id")
    .aggregateMin("amount")
    .aggregateMax("amount")
    .aggregateSum("amount")
    .aggregateAverage("amount")

If you notice carefully, we can specify fields inside the aggregation function. For instance, in the above example, we have used the amount field inside the sum aggregation to specify that we want to sum the values of the amount field. You can also specify multiple fields inside an aggregate function.

Grouping data in aggregations

You can use the group argument to group the data by one or more columns.

Example: Fetch the category wise max expenditures of each user. We need to group the data by user_id and category here:

query {
  expenditures(group: ["user_id", "category"]) @postgres {
    aggregate {
      max {
        amount
      }
    }
  }
}
const { status, data } = db.get("expenditures")
    .groupBy("user_id", "category")
    .aggregateMax("amount")

Have a technical question?

Improve the docs!