Aggregations
Aggregations define server-side query builders for cases that need Mongo aggregation stages such as $group, $project, $lookup, and $unwind.
Use regular Queries for simple $match and $sort cases.
Define An Aggregation
Aggregation files start with _ and live under the collection folder:
The file name becomes the aggregation name. models/users/_byRole.ts is registered as _byRole on the users collection.
Subscribe
Import the aggregation and subscribe to it:
In React:
Callback Arguments
The aggregation callback receives two arguments:
params is the object passed to sub(_aggregation, params) or useSub(_aggregation, params).
context contains:
collection: collection name this aggregation runs against.session: request session. By default it is typed as{ userId?: string }.isServer: whether the aggregation is being evaluated from server-side code.
Return either a Mongo aggregation pipeline array:
Or an aggregation query object:
Output Types
The first generic is the full subscription result shape.
For row-like results:
For document rows, use the schema type:
For metadata output, pass the object shape:
Then the subscribed signal follows that shape:
Row Ids
Aggregation result rows are not always real documents. getId() and getIds() only expose usable string ids:
Rows with a string _id or id return that value. Rows without one, or with a non-string id such as a numeric $group key, return undefined from getId() and are omitted from getIds().
Session Types
By default, context.session is typed as:
You can provide a custom session shape as the second generic:
If you also want to specify the collection type, pass session as the third generic:
For one-off code, inline callback annotations also work:
Client Security
Aggregation files contain server code. The TeamPlay Babel plugin replaces aggregation() calls in client builds with aggregation headers:
The server pipeline implementation is removed from the client bundle. This is why aggregation functions should be defined in models/<collection>/_name.ts files and imported from there.