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, 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. 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,$lookup,$unionWith,$graphLookup,$collStatsor$indexStats— as a stage or nested at any depth — is rejected with aForbiddenPipelineError(.findingslists operator, stage and path). Since 1.6.3 the server refuses$function,$accumulator,$where,$out,$mergeand$currentOpitself (403, code4031), but it still runs$lookup,$unionWithand$graphLookupacross collections (and$collStats,$indexStats), so this check stays as early feedback and as the gate for those. filteris a Lucene filter (the syntax of the document list) that the server applies as the first$match(aggregate?filter=, server 1.7.0), so an aggregation can follow what a table shows. It travels in the URL: over ~1 800 encoded characters it throws aFilterTooLongErrorbefore any request (describeAggregationErrorturns it into a message).- Stats stages are opt-in.
$collStatsand$indexStatswork on the server (storage numbers, per-index usage) but 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). It is for the module's own storage and index-usage calls; the aggregation builder never sets it. Ordinary results are never stripped (a document may have a field calledhost). - An empty result is an empty page. Since server 1.6.1 an aggregation with no documents answers
200 []with a count of0. Older servers (1.5.x) answered500 "Index 0 out of bounds for length 0", which is no longer special-cased and rejects like any other error.
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 (server 1.8.1), 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 }. 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. This is how the field statistics are computed: the server's own getSchemaAnalysis is not used: the client-side sample needs no extra request and behaves the same on every server version. (Up to 1.5.x that endpoint returned an accumulation of every analysis since the server started, across collections — an information leak; it is clean since 1.6.1, re-verified on 1.6.3, so it could be offered for whole-collection scans.)
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
Verified against MongoCamp 1.5.10 and unchanged on 1.6.3 (2026-11-03):
- results are plain JSON: dates as ISO strings without milliseconds,
_idas a hex string, 64-bit integers as bare numbers with every digit —runAggregationandlistDistinctread the response text themselves and return an integer beyond ±(2^53 − 1) as its exact digit string, because the generated client'sJSON.parsewould round it ($numberInt/$numberDecimalwrappers in a result become numbers); distinctanswers with native 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