Aggregations
Prisma Client provides powerful aggregation capabilities to compute values across your data.count()
Count the number of records:Basic Count
Filtered Count
Count by Field
count() method is a convenience wrapper around aggregate(). It desugars your query into an aggregation operation.
Source: /home/daytona/workspace/source/packages/client/src/runtime/core/model/aggregates/count.ts:12-48
Count Relations
See Relations - Relation Count for counting related records.aggregate()
Perform aggregations like sum, average, min, and max:Available Aggregations
Filtered Aggregations
Aggregation Types
Count records or non-null values
Sum numeric fieldsReturns
null if no records match.Average of numeric fieldsReturns
null if no records match.Minimum value (works with numbers, dates, strings)
Maximum value (works with numbers, dates, strings)
groupBy()
Group records and compute aggregations per group:Basic Grouping
Multiple Group Fields
Aggregations per Group
Filter Before Grouping (where)
Filter After Grouping (having)
Sort Groups
Paginate Groups
Practical Examples
Top Users by Post Count
Daily Signups
Average Order Value by Customer
Product Sales by Category
MongoDB-Specific Aggregations
MongoDB providesaggregateRaw() for pipeline aggregations:
/home/daytona/workspace/source/packages/client/tests/functional/0-legacy-ports/aggregate-raw/tests.ts:45-83
Limitations
Field Types
_sumand_avg: Only numeric fields (Int,Float,Decimal)_minand_max: Numeric, date, and string fields_count: All fields
Null Handling
Performance
- Aggregations scan the entire result set
- Use
whereto filter before aggregating - Add indexes on grouped fields and filtered fields
- For large datasets, consider:
- Materialized views
- Pre-computed aggregations
- Database-specific optimizations
Combining with Transactions
Next Steps
Transactions
Ensure data consistency with transactions
Filtering & Sorting
Advanced where clauses for aggregations