> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mirage.strukto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# MongoDB

> Virtualize MongoDB databases from Node or the browser.

`MongoDBVFS` turns MongoDB databases into a read-only tree: every collection
and view is a folder holding its sampled schema and its documents as JSON
lines. Set up the connection URI as in [MongoDB setup](https://docs.mirage.strukto.ai/home/setup/mongodb.md).

## Install

```bash theme={null}
npm install @struktoai/mirage-node mongodb
```

## Configure

```ts theme={null}
import { MongoDBVFS, MountMode, Workspace } from '@struktoai/mirage-node'

const mongo = new MongoDBVFS({
  uri: process.env.MONGODB_URI!,
  databases: ['sample_mflix'],
})
const ws = new Workspace({ '/mongodb': mongo }, { mode: MountMode.READ })

const result = await ws.shell('head -n 3 /mongodb/sample_mflix/collections/movies/documents.jsonl')
console.log(result.stdoutText)
await ws.close()
```

`databases` limits the tree to those databases.
`elideFields: { 'sample_mflix.movies': ['plot_embedding'] }` drops heavy
fields, such as embeddings, from what an agent reads.

### Fields

**timeout** `number` (default: DEFAULT\_TIMEOUT)

Seconds a request may wait to connect, or between two reads of its answer, before it fails; a download that keeps flowing is never cut off.

**uri** `string` *required*

MongoDB connection URI in Node; in the browser, the URL of a backend route that holds the connection URI.

**databases** `string[]` (default: null)

Databases to mount; others are hidden. Unset or empty mounts every database except `admin`, `config` and `local`.

**maxDocLimit** `number` (default: 5000)

Most documents one `tail -n` read of `documents.jsonl` fetches; a larger count on a collection that holds more is refused (`File too large`).

**elideFields** `object` (default: \{})

Fields dropped from `documents.jsonl`, keyed by `<database>.<collection>` (a view's name works too); a dotted path such as `nested.path` drops a nested field.

Fields marked secret are redacted in snapshots.

## Authentication

The user in the URI needs to read the databases the mount shows: the built-in
**Only read any database** role on Atlas, or `read` on each database.

## Layout

```text theme={null}
/mongodb/
  sample_mflix/
    database.json
    collections/
      movies/
        schema.json
        documents.jsonl
    views/
      top_movies/
        schema.json
        documents.jsonl
```

The tree mirrors MongoDB's cluster, database, collection and view. The
database folder always appears, even when `databases` names one database.
Listings show databases, collections, views and their fixed files, never one
entry per document.

* `database.json`: the collection and view names, without counts.
* `schema.json`: field paths and the BSON types seen in the first 100
  documents in `_id` order, the indexes and the `$jsonSchema` validator if one
  is set. Views have no indexes. Unchanged data reads as identical bytes.
* `documents.jsonl`: one document per line in
  [Relaxed Extended JSON](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/),
  in `_id` order:

```json theme={null}
{"_id":{"$oid":"573a1390f29313caabcd4135"},"title":"Casablanca","released":{"$date":"1943-01-23T00:00:00Z"},"runtime":102}
```

## Behavior

* **Read-only:** the mount only reads; no command changes the database.
* **Streaming:** `cat`, `grep`, `jq` and `head` read documents in batches, and
  `head` stops after its count. Commands that need the whole input, such as
  `sort` or `jq -s`, still buffer it, so read a large collection in bounded
  slices.
* **Read limit:** `tail -n` with a count past `maxDocLimit` on a collection
  that long fails with `File too large` rather than printing fewer lines.
* **Elided fields:** fields under `elideFields` are dropped from
  `documents.jsonl`, for `cat` and `tail -f` alike, and keep their type in
  `schema.json`. Nested paths use dots, such as `metadata.embedding`.
* **File size:** `documents.jsonl` is rendered on demand, so `stat` and `ls -l`
  show `-` for its size and `du` counts `0`. `wc -c` measures the bytes and
  `wc -l` counts the documents; both may scan the collection. A nonempty
  `ls -l` prints `total ?`.
* **Following inserts:** `tail -f` prints the last lines, then follows new
  inserts through a change stream. That needs a replica set on MongoDB 5.0 or
  later, which Atlas is; on a standalone server, and on a view, it polls.

## Browser

The browser `MongoDBVFS` from `@struktoai/mirage-browser` sends HTTP requests
to a backend route, which keeps the connection URI on the server. Its `uri` is
that route.

```bash theme={null}
npm install @struktoai/mirage-browser
```

```ts theme={null}
import { MongoDBVFS, MountMode, Workspace } from '@struktoai/mirage-browser'

const mongo = new MongoDBVFS({ uri: '/api/mongo' })
const ws = new Workspace({ '/mongodb': mongo }, { mode: MountMode.READ })
```

* The repository's
  [Vite middleware](https://github.com/strukto-ai/mirage/blob/main/examples/browser/scripts/mongo_proxy.ts)
  serves the database listing for local development. It does not yet serve
  document streams or schema reads.

## Integration

MongoDB answers these commands through its own API, so fewer documents are
read. See [Integration](https://docs.mirage.strukto.ai/home/integration/overview.md).

* `grep` and `rg` on one file: a filter on the server sends only the documents
  that may match. `grep -r` on a folder does the same for each
  `documents.jsonl` under it.
* `tail -n N`: the last N documents by `_id`, sorted on the server.
* `wc -l`: `countDocuments()` on the server.
* `tail -f`: a change stream yields each new insert.

For one plain text, the filter matches it in any case against every key and
string of a document, eight levels deep, in the `_id` order a plain read takes.
A document nested deeper, or holding a value the filter cannot look into
(binary, a regex, code), is always sent. MongoDB still scans the collection,
but only those documents are sent. The file is read as usual when the text
holds anything but ASCII letters and spaces, or could match an Extended JSON
key (`$oid`, `$date`, `$numberLong`), a JSON literal (`true`, `null`) or an id
(a word of hex letters only, such as `ada`). `schema.json` and `database.json`
are always read, and `-m` stops the cursor early.

## VFS.md

The [VFS.md](https://docs.mirage.strukto.ai/home/setup/vfs-md.md) an agent reads with MongoDB mounted at `/<path>`.

> [tab] Rendered
>
> **Virtual Filesystem**
>
> | Path | Description |
> | - | - |
> | `/<path>` | `mongodb`, read |
>
> **VFS Layout**
>
> **`/<path>`**
>
> ```text theme={null}
> /<path>
>   <database>/
>     database.json              # collection and view names
>     collections/<collection>/
>       schema.json              # sampled field types, validator, indexes
>       documents.jsonl          # streamed BSON Extended JSON documents
>     views/<view>/
>       schema.json
>       documents.jsonl
> ```
>
> * Read `database.json` first, and `schema.json` before a large
>   `documents.jsonl`.
> * Sizes show as `-`; `wc -c` and `wc -l` count on demand and may scan
>   the collection.
>
> **Supported Unix Commands for VFS**
>
> Unix commands work on each path as on a local filesystem, as far as the path supports them:
>
> | Path | Supported |
> | - | - |
> | `/<path>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep` and `rg` ask `mongodb` for the matching lines. `tail` and `wc -l` ask `mongodb` instead of reading a file. |
>
> **Limitations of Unix Commands for VFS**
>
> Where a path differs from a local filesystem:
>
> | Path | Limitations |
> | - | - |
> | `/<path>` | Read only: no command changes files. `grep -r`, `find` and `du` stop after 1000 files; a glob matching more, `tar -c`, `cp -r` and `rm -r` are refused. |
>
> Run `man <cmd>` or `<cmd> --help` for one command's usage.

> [tab] Raw
>
> ````markdown theme={null}
> ---
> name: workspace-filesystem
> description: The virtual filesystem layout of this workspace.
> ---
>
> # Virtual Filesystem
>
> | Path | Description |
> | --- | --- |
> | `/<path>` | `mongodb`, read |
>
> ## VFS Layout
>
> ### `/<path>`
>
> ```text
> /<path>
>   <database>/
>     database.json              # collection and view names
>     collections/<collection>/
>       schema.json              # sampled field types, validator, indexes
>       documents.jsonl          # streamed BSON Extended JSON documents
>     views/<view>/
>       schema.json
>       documents.jsonl
> ```
>
> - Read `database.json` first, and `schema.json` before a large
>   `documents.jsonl`.
> - Sizes show as `-`; `wc -c` and `wc -l` count on demand and may scan
>   the collection.
>
> ## Supported Unix Commands for VFS
>
> Unix commands work on each path as on a local filesystem, as far as the path supports them:
>
> | Path | Supported |
> | --- | --- |
> | `/<path>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). `grep` and `rg` ask `mongodb` for the matching lines. `tail` and `wc -l` ask `mongodb` instead of reading a file. |
>
> ## Limitations of Unix Commands for VFS
>
> Where a path differs from a local filesystem:
>
> | Path | Limitations |
> | --- | --- |
> | `/<path>` | Read only: no command changes files. `grep -r`, `find` and `du` stop after 1000 files; a glob matching more, `tar -c`, `cp -r` and `rm -r` are refused. |
>
> Run `man <cmd>` or `<cmd> --help` for one command's usage.
> ````


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.