MongocampCollectionData
Paginated, filterable, sortable document table for a collection, with insert/edit/delete, import, bulk edit and bulk delete, a filter builder, page export and a column menu, and — for GridFS bucket collections — per-row download and bucket upload.
Usage
<template>
<MongocampCollectionData collection-name="myCollection" />
</template>Props
| Prop | Type | Description |
|---|---|---|
collectionName | string | Required. Collection to browse. |
aggregatePath | string | Base path of the page rendering MongocampAggregationBuilder. With it the toolbar has an Aggregate the matching documents link to <aggregatePath>/<collectionName>/aggregate?filter=<applied Lucene> (the page passes the query's filter to the builder). No link without it (default empty). |
infoPath | string | Base path of the page rendering MongocampCollectionInfos; the "index created" toast links to <infoPath>/<collectionName>. Default /secured/admin/collections. |
persistState | boolean | Remember page size, sort and hidden columns per collection in localStorage (see useMongocampPersistedState). Default true; the quick search and filters are not remembered. |
stateKey | string | Extra key part so two tables over the same collection keep separate state. |
hideRefresh | boolean | Hide the component's own reload button, e.g. when the page calls the exposed refresh() from its own header. Default false. |
stickyActions | boolean | Keep the row actions column (view / edit / delete) fixed at the right edge while the table scrolls sideways. Default true; false lets it scroll with the other columns. |
stickyId | boolean | Keep the first data column (usually _id) fixed at the left edge while the table scrolls sideways. Default false. |
pageSizes | number[] | Page sizes offered in the size select. Default [10, 20, 50, 100]; non-positive or fractional entries and duplicates are dropped (an empty result falls back to the default). |
defaultPageSize | number | Size a collection opens with until a size is remembered for it. Default 20; if it is not one of pageSizes, the second offered size is used. A remembered size counts only while it is still offered. |
In a page with its own header
The component can hand its toolbar to the page around it:
refresh()is exposed — call it through a template ref from your own reload button, and sethideRefreshto drop the built-in one.toolbarslot — your own buttons, placed beside the built-in ones.changedevent — emitted after documents were inserted, saved, deleted, bulk-edited or imported, or a file was uploaded, once the component has reloaded. Never on a failed or cancelled action, never on a plain reload.
<script setup lang="ts">
const list = useTemplateRef<{ refresh: () => void }>('list')
</script>
<template>
<header>
<h1>My title</h1>
<UButton icon="i-lucide-refresh-cw" @click="list?.refresh()" />
</header>
<MongocampCollectionData ref="list" :collection-name="name" hide-refresh @changed="reloadOtherLists">
<template #toolbar>
<UButton>Mine</UButton>
</template>
</MongocampCollectionData>
</template>Columns
Columns are derived from the first fetched row's keys (_id first, metaData last, everything else A–Z). The first data column stays pinned while the table scrolls sideways, so rows stay identifiable on narrow screens; the column menu hides and shows the rest.
Index this field
Managers (useMongocampRoles().isManager) get a small menu next to the sort button of each data column: Create ascending index / Create descending index. It makes one plain single-field index through useMongocampIndex().createIndexForField. It is not offered for GridFS bucket collections, for _id (always indexed) or for the metaData object, nor to non-managers.
On success a toast names the index and offers View indexes (the info page, see infoPath). On failure a toast shows the server's own message (a conflicting existing index, for example) with the database address removed. Asking for an index that already exists is not an error: MongoDB treats an identical request as a no-op and the server answers with the same index name. Compound, unique, text and expiring indexes stay in the Indexes card of MongocampCollectionInfos.
Cell rendering
- ISO timestamp strings (date and time, e.g.
2018-02-02T22:23:44Z) and MongoDB$dateextended JSON → locale-formatted date string, decided per cell — a column that mixes both formats renders consistently. Date-only strings (2018-02-02) are left as they are - MongoDB
$oid→ monospaced ID string metaDataobjects (withcreated/updatedfields) → structuredcreated/updated/byrows- Other scalar values longer than 60 characters are truncated with
…; the full value is available via a hover tooltip - All other objects and arrays → icon button (
{}/ list); click opens a modal with pretty-printed JSON
Filtering & sorting
- The search input is debounced (300ms) and built with
useMongocampQuery'slike/orhelpers (col1:"*term*" OR col2:"*term*") across all string-typed columns — disabled until at least one such column exists. - Column headers are clickable and trigger a server-side sort (
field/-field) viadocumentApi.listDocumentsRaw. - The Filters button (badge = number of active conditions) opens a
MongocampFilterBuilderpanel. Apply filters reloads from page 1; each applied condition shows as a removable chip with a Clear filters link. The builder and the search input narrow the result together (AND).- The fields offered come from the rows on the first page, with their types inferred from the values.
_idis offered with the exact operators only (equals,notEquals,oneOfwith 24-character hex ids; server 1.6.1 or later — older servers reject_idfilters), no arrays and objects (no operators for them). The button is disabled for an empty collection. - Applied filters, the panel and the draft are reset when
collectionNamechanges and by the reload button. - Value suggestions: focusing the value of a text field's equals / not equals / is one of condition lists that field's distinct values (one
distinctrequest per field, cached until the collection changes or the table is reloaded; sorted, up to 100). A field with more than 100 distinct values (names, ids) gets no suggestions — an arbitrary hundred would only mislead — and a failed lookup quietly leaves a plain input.
- The fields offered come from the rows on the first page, with their types inferred from the values.
Toolbar
- Filters — see above.
- Import documents — opens
MongocampImport: load a JSON or CSV file, check the preview and insert it in batches. Not shown for GridFS bucket collections; the table reloads when rows were imported. - Columns — a checklist of every data column; unchecked columns are hidden (and left out of the CSV export). Resets when you reload or switch collection.
- Export — downloads the rows on the current page, as JSON (full documents, extended JSON unwrapped to plain values) or CSV (visible columns; nested values as JSON; RFC 4180 quoting). No extra request is made, so export what you need page by page, or raise the page size first. An integer beyond 2^53 is written with every digit (a bare number in JSON). To export the whole collection or everything a filter matches, use
useMongocampExportAll. - Rows per page — 10, 20 (default), 50 or 100; changing it reloads from page 1.
- Reload — refetches and resets sorting, search, filters and column choices.
Selecting, editing and deleting several documents
The first column is a checkbox column (with select-all for the current page). While rows are selected a bar shows N selected · Delete selected · Edit selected · Clear selection (MongocampBulkDelete).
Edit selected (
MongocampBulkEdit) sets one scalar field to one value on every selected document, in one request per 100 documents. Fields that were not updated stay selected and are reported;metaDatais not touched.Delete selected asks for confirmation first, listing the first few ids.
The selection is dropped whenever the table reloads — paging, sorting, searching, filtering, page size — so rows you can no longer see are never deleted.
Deletion is one
deleteManyrequest for the selection (with a one-by-one fallback); if some fail the rest are still deleted, the failed ones stay selected and the modal reports how many failed and why. Documents whose_idis not a 24-character hex string can only be deleted one by one, and cannot be bulk-edited.GridFS bucket collections (
*.files/*.chunks) have no selection: deleting those documents one by one would orphan the other half of a file. UseMongocampBucketFilesfor buckets.
When loading fails
A failed load shows a MongocampErrorAlert above the table (retry, or "log in again" when the session has expired) instead of an empty table, and an empty result shows an empty state. A search or filter the server rejects answers 400 (MongoCamp server 1.6.3+ sends CORS headers on errors, so the status is readable); when that happens while a search or filter is active the alert says "The filter could not be applied" and offers Clear filters (which drops the search and every condition). A 401 is shown as an expired session; any other failure keeps the generic message. No extra request is made.
Without a write grant
The table is read-only for a user whose grant for this collection has no write — no insert, import, edit, delete or row selection (so no bulk edit or delete either); rows, filtering, sorting, the column menu and export stay. The decision comes from the grants in the session profile (useMongocampPermissions): administrators, server proxy mode, a profile without a grant list and GridFS bucket collections always keep every control, and the server refuses a write without a grant anyway — this only hides what could not work.
Insert / Edit / Delete
- Insert / Edit — opens a form generated by
@sfxcode/nuxt-ui-formkit'sFUAutoForm, which infers a FormKit schema directly from the currently-loaded page of rows (unwrapped viauseMongocampExtendedJson) — scalar fields, nested objects, and arrays (including arrays of objects, withFUAutoForm's own add/clone/delete row controls) all render as real inputs instead of raw JSON._idis stripped from the samples/form data before they ever reachFUAutoForm, so it never appears as an editable field — it is not something a document's own value should drive. Saving rewraps the form data back throughuseMongocampExtendedJson, stampsmetaDataviauseMongocampDocument'sensureMetaData, then callsdocumentApi.insert(any_idis stripped before sending). FormKit's internalslotsform entry is dropped first so it never lands in a document. - Large integers stay exact. MongoCamp sends a 64-bit integer with every digit, but the generated client's
JSON.parserounds anything beyond 2^53 (9007199254740993would show as9007199254740992,9223372036854775807as9223372036854776000). The component reads the response text itself (utils/bigIntJson.ts): such an integer is shown, edited and exported as its exact digits, and written back as{ $numberLong }when you change it. An untouched one is never part of an edit request. In the edit form it is a text field, and the filter builder still offers number operators for it. - Edit sends only what changed — the edited document is compared with the row it was opened from (values compared as plain values, so a date or number that merely round-tripped through its extended-JSON wrapper — or a date the server prints without its zero milliseconds — is not a change) and sent with
documentApi.updateDocumentPartial: a changed leaf of a nested object as a dotted key (nested.y), an array or a changed$date/$oid/number wrapper as a whole value, a removed field as$unset, plusmetaData.updatedBy/metaData.updated. A concurrent change to another field of the same document is therefore not overwritten, and fields the form never saw are simply not part of the request. Nothing changed ⇒ the dialog closes without a request. If the server reportsmatchedCount: 0the document is gone and the dialog shows "The document no longer exists." A change a partial update cannot express (a top-level field name containing a dot or starting with$) falls back to the fulldocumentApi.update. Helpers:utils/documentDiff.ts. - Empty-collection fallback — if the currently-loaded page has zero rows, there's nothing to infer a schema from, so Insert falls back to a raw-JSON textarea modal instead (Edit never hits this path, since editing requires an existing row to have been loaded in the first place).
- Delete — confirmation modal, then
documentApi._delete.
GridFS bucket collections
When collectionName ends in .files or .chunks (i.e. you're browsing a GridFS bucket), the toolbar and actions column change:
- The Insert (+) button is replaced with an Upload button — picks a file and uploads it to the underlying bucket via
fileApi.insertFile. - Each row gets a Download button that fetches the file (by
_idon.filesrows, byfiles_idon.chunksrows) and triggers a browser download using the real filename.
This logic is provided by useMongocampBucket — see that page for the bucket-naming convention and how file IDs are resolved from each row shape.
Related composables
useMongocampCollectionuseMongocampBucketuseMongocampQuery/useMongocampQueryBuilder— for building custom Lucene filtersuseMongocampExtendedJson— extended-JSON unwrap/rewrap that feedsFUAutoForm's Add/Edit modaluseMongocampDocument—ensureMetaDatastampsmetaDataon insert/updateuseMongocampFilterBuilder,useMongocampExport,useMongocampBulkDelete— the logic behind the filter panel, page export and bulk deleteuseMongocampImport— the batched insert behind the import dialog
Viewing documents
Every row has a View button (also without a write grant) that opens the document in a drawer with MongocampDocumentView: typed values, copy of path and value, tree or JSON. The row appears at once and is replaced a moment later by the typed read of the document (extendedJson=canonical, see below), so the viewer shows the real types — an id, a date, int / long / double / decimal, and text that merely looks like a date — instead of what plain JSON allows (if that request fails the table's row stays). A Table | JSON switch in the toolbar shows the page as JSON text.
Filters
The filter builder's field list comes from the server's field analysis for the whole collection (useMongocampFieldTypes, fields/detail), not from the rows on screen: a field the current page lacks is still offered, nested paths (address.city) are offered and filtered with the server's dotted-path Lucene (verified live: equals, wildcard, ranges, negation), and containers and binary fields are left out. While the analysis loads, or when it fails, the fields of the loaded rows are used as before. It is loaded when the collection changes and after an insert or import.
Charting what the table shows
The Chart a field button (not for GridFS collections) opens a dialog with a field select and a chart (MongocampCollectionCharts) of that field over the documents the table currently matches: the applied Lucene filter (quick search + filter builder) is sent as aggregate?filter= and the server applies it as the first $match. Only fields with something to count are offered — text, numbers, dates, booleans (no _id, objects or arrays). A filter too long for the URL is refused with a message instead of being sent.
Comparing two documents
Compare selected (exactly two ticked rows) reads both documents with their real types (extendedJson=canonical, two parallel requests) and opens MongocampDocumentCompare on them, so an int 5 and a long 5, or a double and a decimal with the same text, show up as a type change with both types named. If a read fails, the table's rows are compared and the dialog says that types were not compared.
Inserting with the collection's types
An insert (and a field the edited document did not have) is written with the collection's field types from useMongocampFieldTypes: a field that holds text everywhere stays text even when the new value looks like a timestamp (written as { $string } — the server would otherwise store it as a date), an int field is written as { $numberInt }, a long keeps its digits. Fields with more than one type found, or without a known type, are written as plain JSON and the old rule applies (a timestamp-shaped text becomes a date).
Typed reads
The table's own page is a plain read (ids and dates are strings, a long beyond 2^53 is read from the response text so it stays exact): putting every number in a wrapper would about triple its size. Everything that needs the real types reads one document with extendedJson=canonical (server 1.8.1) — View and Edit. Canonical writes { $oid }, { $date }, { $numberInt }, { $numberLong }, { $numberDouble }, { $numberDecimal }, and { $string } for text that looks like a timestamp. (relaxed is not used: it writes int, long and double all as a bare number, so the types cannot be told apart.)
Edit always starts from that typed document (one request), and the save writes every value back as the type it had: an edited int goes back as { $numberInt } instead of becoming a long, a decimal stays a decimal, and text such as "2026-01-01T00:00:00.000Z" is sent as { $string } — otherwise the server stores a timestamp-shaped string as a date (verified live: that is what happens to a plain string). Untouched fields are not sent at all. The raw-JSON editor shows the canonical wrappers and parses them back as they are.
Query bar
Below the toolbar sits a MongocampQueryBar: the visual filter (button, count and chips), a sort (it follows clicks on the column headers), the fields to load and the recent/saved queries of the collection. The quick search stays as the simple mode and is ANDed with the bar's filter.
With fields chosen, only those are requested (projection); the other columns are hidden and Edit loads the complete document first, so a partial row is never written back. A failed load shows a toast and the form stays closed.
Select all matching
Tick the header checkbox to select the page. When more documents match the current filter, the selection bar offers Select all N matching documents. The table counts the matches (GET …/documents/count, one request) and Delete selected / Edit selected then work on the filter, not on a list of ids: one deleteMany / updateMany request with the Lucene filter of the table (useMongocampBulkByFilter).
- No cap, no chunks: a million matches are one request. (Before server 1.7.0 the table read every id, capped at 10 000.)
- Confirmation: deleting every match needs the collection name typed; the count is on the button.
- Not a snapshot: the server applies the filter when the request arrives. If the count differs from what the list showed (documents added or removed meanwhile) the bar says so, and the result is reported (
Deleted 500 of 500 documents). - Failure: the dialog stays open with the server's message and the selection stays, so a retry is one click.
- An empty filter (no quick search, no query) sends
matchAll=true— the typed collection name is the only guard. - Reloading, paging, filtering or sorting drops the selection.
Export all matching
The export menu has Export all matching… next to the page exports: it opens MongocampExportAll with the current filter, sort and fields and the match count, and the server streams every matching document as JSON, NDJSON or CSV (no document cap; a file cut short is reported as incomplete).