useMongocampAggregation
Aggregation, distinct values and sampling over collectionApi.aggregate / distinct, with timeouts, defensive result handling and readable errors. It is the engine behind MongocampAggregationBuilder, the value suggestions in MongocampFilterBuilder and the field statistics in MongocampCollectionInfos, and works in session and server proxy mode alike (it calls useMongocampClientApi).
const { runAggregation, listDistinct, listFieldNames, listFieldDetails, sampleDocuments, describeAggregationError } = useMongocampAggregation()
const { rows, total, pages, page } = await runAggregation('customers', [
{ stage: '$group', value: { _id: '$country', n: { $sum: 1 } } },
{ stage: '$sort', value: { n: -1 } },
], { page: 1, rowsPerPage: 20 })runAggregation(collection, pipeline, { page, rowsPerPage }, { allowStatsStages, filter, filterCaseInsensitive, skipCount, signal })
pipeline is { stage: '$match', value: <JSON> }[] — value is real JSON (a number for $limit, an object for most stages), not a string. Returns:
{ rows: Record<string, unknown>[], total: number, pages: number, page: number }total, pages and page come from the server's x-pagination-* headers (falling back to the row count, 1 and the requested page); rowsPerPage defaults to the server's 100. The server sends relaxed Extended JSON; every row is unwrapped to plain values ({ $oid } → hex text, { $date } → ISO text, numbers → numbers, an integer beyond ±(2^53 − 1) → its exact digit string). Entries that are not objects are dropped. The request has a 30 s timeout and always sends allowDiskUse: false (the server requires the field).
- Refuses forbidden pipelines. Before any request, a pipeline using
$out,$merge,$function,$accumulator,$where,$currentOp,$listSessions,$collStatsor$indexStats— as a stage or nested at any depth — is rejected with aForbiddenPipelineError(.findingslists operator, stage and path). That is the default deny-list of server 2.0, which refuses them itself too (403, code4031; its list is in the capabilities), so this check is early feedback. Joins ($lookup,$unionWith,$graphLookup) are allowed — the server checks the read grant of every collection they read (403, code4032). - Hides MongoCamp's user secrets. A pipeline that reads
mc_users(directly or by a join) returns nopassword/apiKeyat any depth, and one that refers to them by path is refused with aForbiddenPipelineErrorwhose finding hassensitive: true(describeAggregationErrorexplains it).listDistinct('mc_users', 'password' | 'apiKey')returns no values without a request. filteris a Lucene filter (the syntax of the document list) that the server applies as the first$match, so an aggregation can follow what a table shows. It travels in the request body (filterof the aggregate request, server 2.2), so it can be of any length.filterCaseInsensitive: truematches its wildcards without regard to case (a query parameter, sent only with a non-empty filter).- Stats stages are opt-in (deprecated).
$collStatsand$indexStatsare refused by the server by default (AGGREGATION_STAGES_DENIED; server 2.7.2 also upgrades an older stored list that allowed them) — only a server whose administrator allows them again runs them. Index usage comes fromuseMongocampCollectionStats().getIndexUsage(GET …/index/stats), storage numbers fromgetStorage. Where they run, every result row carries the database server's address (host) and its<database>.<collection>name (ns).runAggregation(collection, pipeline, paging, { allowStatsStages: true })lets a pipeline use exactly those two — every other denied operator stays refused — and removeshostandnsfrom the top level of every row (stripServerFields). No module call sets it any more, and the aggregation builder never did. Ordinary results are never stripped (a document may have a field calledhost). skipCount: truesendscount=none: the server skips counting,totalis then the number of rows returned andpagesis1. Used where only the rows matter —sampleDocuments, the index usage ($indexStats) and the builder's stage previews.- An empty result is an empty page (
200 [], count0).
runAggregation's fourth argument also takes signal: aborting rejects the call (an AbortError) on top of the 30 s timeout — the builder's stage previews use it to drop a run that is out of date.
listFieldDetails(collection, { sampleSize?, depth? })
Every field of a collection with the types of its values — GET …/fields/detail, 15 s timeout. A flat list, one entry per path; nested fields are address.city, the elements of an array tags[]; each entry has the MongoDB $type names found in a sample with how often ({ path: 'age', types: [{ type: 'long', count: 15 }, { type: 'string', count: 5 }] }). sampleSize (server default 1000) and depth (default 3) tune it. MongocampCollectionCharts detects the chart kind from it; the pure helpers (valueKindOfType, dominantKindOfField, fieldPathsOf) are in utils/fieldDetails.ts.
listFieldNames(collection)
The field paths of a collection, nested ones included (address.city), sorted; the elements of arrays (tags[]) are left out because no stage can name them. Built from listFieldDetails. For suggestions only — the builder's templates offer them while you type.
listDistinct(collection, field, limit = 100)
Distinct values of a field: { values, total, truncated }. The distinct route answers plain JSON (ids and dates as text, a long beyond 2^53 as a bare number, read from the response text so it keeps its digits). Only strings, numbers and booleans are returned — null (which is what the server answers for a field nobody has), arrays (not unwound) and objects are dropped. The values are in no particular order. truncated is true when the field has more distinct values than limit. 15 s timeout.
sampleDocuments(collection, size = 500)
A random sample in one page — an aggregation with $sample, size clamped to 1–1 000. Same result shape as runAggregation; the count is skipped (count=none). This is how the field statistics are computed — no extra request; the server's own analysis of every document is the separate getSchemaAnalysis of useMongocampAdmin.
describeAggregationError(error)
Async, because the server explains a failure in the response body. Returns { kind, message }:
kind | When |
|---|---|
forbidden | a ForbiddenPipelineError; the message names the operator |
retryable | an unexpected 405 (an intermittent proxy response) |
mongo | MongoDB rejected a command; message is only MongoDB's own text |
network / unauthorized / forbidden-access / other | the shared mapping of useMongocampError |
The server's raw error contains the address of the database server (… on server host:port. …); it is removed from every message this returns.
What the server does that you might not expect
- aggregation results are relaxed Extended JSON (
{ $oid },{ $date },{ $numberLong }beyond 2^53,{ $numberDecimal },{ $string }for date-looking text) —runAggregationreads the response text itself and unwraps it, because the generated client'sJSON.parsewould round a long; distinctanswers with native plain values although the generated client types it asstring[];- the generated client types a stage's
valueasstring; the server wants JSON (the composable casts).
Related
MongocampAggregationBuilderuseMongocampQuery— Lucene filters for the document list; aggregation$matchuses MongoDB query syntax instead