Aggregate
Query Operations
Aggregate
Execute MongoDB aggregation pipelines with automatic RBAC enforcement
POST
Aggregate
Overview
The aggregate endpoint allows you to execute complex MongoDB aggregation pipelines on your collections. The pipeline is automatically enhanced with RBAC filters to ensure users only access data they have permission to read.Request
The name of the collection to aggregate
Array of aggregation pipeline stages. Each stage is an object with MongoDB aggregation operators.Maximum stages: 20 (configurable)
Basic Aggregation Example
Advanced Pipeline Example
Response
Array of documents resulting from the aggregation pipeline. The structure depends on your pipeline stages, particularly
$group and $project operations.Response Example
Aggregation Pipeline Stages
$match - Filter Documents
$group - Group and Accumulate
$sum: Calculate sum$avg: Calculate average$min,$max: Find minimum/maximum$first,$last: Get first/last value$push: Build array of values$addToSet: Build array of unique values
$project - Reshape Documents
$sort - Sort Documents
$limit - Limit Results
$skip - Skip Documents
$lookup - Join Collections
$unwind - Deconstruct Arrays
$addFields - Add Computed Fields
RBAC Enforcement
Fromhandlers_query.go:353-388:
The aggregation pipeline is automatically enhanced with RBAC filters:
- RBAC filter injection: A
$matchstage with RBAC filters is prepended to the pipeline - Filter merging: If your pipeline starts with a
$match, the RBAC filter is merged with it - Automatic enforcement: Users only see aggregated data from documents they have permission to read
Pipeline Limits
Fromhandlers_query.go:345-351:
Maximum 20 stages by default (configurable via
scalability.max_aggregation_stages)handlers_query.go:404-410:
Maximum 10,000 results by default (configurable via
scalability.max_result_size)Common Use Cases
Sales Analytics
User Engagement Report
Top Performers
Error Responses
Error code:
collection_not_found: Collection does not existforbidden: User lacks aggregate permissionbad_request: Invalid pipeline (too many stages, invalid syntax)internal_error: Aggregation execution failed
Human-readable error message
Additional error context
Error Examples
Performance Considerations
- Start with $match: Filter data early in the pipeline to reduce documents processed
- Use indexes: Ensure fields used in
$matchand$sortare indexed - Limit early: Use
$limitas soon as possible if you don’t need all results - Avoid $lookup on large collections: Joins can be expensive; consider denormalization
- Monitor result size: Keep aggregation results under the max result size limit
Code Reference
Implementation:pkg/api/handlers_query.go:299-420
Related Endpoints
- List Documents - Simple queries with filtering and pagination
- Count Documents - Count matching documents
- Get Document - Retrieve a single document