Repository navigation
Description
What I'm after
A mongodb connector so ktx can treat a MongoDB database as a primary context source, the same way it already does ClickHouse (#172). We run a fair bit of our data through Mongo before it ever lands in the warehouse, and right now that whole layer is invisible to ktx — the context stops at the SQL side.
Two things make this more than "ClickHouse but a different driver":
- It'd be the first non-SQL connector. Every existing connector is a SQL warehouse (
dialect.ts+information_schema-style introspection + read-only SQL execution). MongoDB has neither. TheKtxScanConnectorcontract still fits via capability flags —readOnlySql: false,formalForeignKeys: false,nestedAnalysis: true— butktx sqlwouldn't apply to a Mongo connection, and it's worth a maintainer sanity-check that the ingest / relationship-discovery path is happy with areadOnlySql: falsesource end-to-end before anyone writes much code. - There's no schema to read — it has to be inferred by sampling documents. That's the only real design decision here, so it gets its own section.
Where I'd start
- New connector under
packages/cli/src/connectors/mongodb/(single-package layout — there is nopackages/connector-*). Nodialect.ts, since it's not SQL. - Add
mongodbto theKtxConnectionDriverunion (src/context/scan/types.ts), a dedicated connection schema insrc/context/project/driver-schemas.ts, and a registration insrc/context/connections/drivers.ts(scopeConfigKey: 'databases'). - Use the official
mongodbdriver. - Map a collection → table and each inferred top-level field → column, so it drops straight into ktx's existing table/column model and relationship discovery.
- Reuse the existing credential/reference resolver (
env:/file:) the other connectors use rather than hand-rolling one. - Strictly read-only:
find/ read aggregation only; reject writes and admin ops.
Schema inference — the one design decision
You can't just randomly sample a collection and call the result "the schema." A collection's shape drifts over time: the newest documents reflect what the data looks like today, while old ones carry fields that were renamed, dropped, or didn't exist yet. So the connector should infer the schema from the most recent N documents, sorted by _id descending — ObjectIds embed a creation timestamp, so this captures the current schema with zero configuration.
I'd keep this as a single canonical behaviour, not a set of selectable strategies — ktx's AGENTS.md is explicit about preferring one strong default over configurable modes, and "newest-N" is the correct default here, not just a convenient one. The only knob I think is justified is a correctness fallback, not a strategy:
order_by— when_idisn't an ObjectId (custom string / UUID keys), "newest" is undefined, so allow naming a field (e.g.createdAt) to order by. Optional; defaults to_iddesc.sample_size— how many recent documents to read (sensible default, e.g. 1000).
Config sketch:
connections:
mongo-prod:
driver: mongodb
url: env:MONGO_URL
databases: [app]
enabled_tables: [app.users, app.orders] # optional collection allowlist
sample_size: 1000
# order_by: createdAt # only when _id isn't an ObjectId(If it later turns out a collection genuinely needs random or hybrid sampling for coverage, that can be argued for separately — I'd rather not ship strategy toggles speculatively. Per-field "this only appears in old documents" provenance/legacy flagging is a possible follow-up, out of scope for a first pass.)
Acceptance criteria
-
mongodbdriver registered and type-checks across the registry/union/schema wiring - Connects via standard
mongodb:///mongodb+srv://strings, with credentials throughenv:NAMEorfile:/path(same as existing connectors), including TLS / Atlas - Selectable database + collection allowlist (the
enabled_tablesequivalent,database.collectionform) - Infers a schema by sampling the newest
sample_sizedocuments (by_iddesc, ororder_by), handling nested documents and arrays, with BSON types mapped into ktx's type model andnullablederived from field presence -
_idtreated as the primary key;formalForeignKeys: false - Read-only; writes/admin rejected;
readOnlySql: false(no SQL execution path for Mongo) - Large collections don't stall a run
- Connector unit tests (schema inference + a mocked client), matching the existing connector test style
- Integration docs under
docs-site/content/docs/integrations/with a real connection-config example - Verified end-to-end with a real
ktx ingestagainst a test Mongo (confirms the non-SQL source flows through ingest)
Open questions
- How to represent deeply nested / polymorphic fields in the semantic layer — dotted paths vs. nested type metadata? Should match whatever relationship discovery already expects.
- Does the ingest / relationship / semantic-layer path fully tolerate a
readOnlySql: false, no-dialect source? (The reason for the end-to-end acceptance criterion above.) - One honest limitation of newest-by-
_id: it tracks insertion time, not last-modified. For collections migrated in place (old docs rewritten without a new_id),order_byon a realupdatedAtis the escape hatch.
Reward
Scope feels comparable to the ClickHouse connector (#172), so I'd guess tier-3 — happy to defer to however you'd actually tier it. See CONTRIBUTING.md.
Happy to claim and take a run at this — floating the design first since the sampling default and the "first non-SQL connector" question are the calls worth aligning on before code.
Activity
andreybavt commentedon Jun 17, 2026
Thanks @Pintouch , we'll review the scope in a bit and will get back to you shortly. But generally adding Mongo support is a great idea
Pintouch commentedon Jun 17, 2026
Thanks @andreybavt, don't hesitate if you have any questions / suggestion, I will be glad to work on this 👍
andreybavt commentedon Jun 17, 2026
Hey @Pintouch, we iterated on the Mongo connector spec and think this should be a good start. Your write-up was most of the way there; the main change is around the dialect, plus answers to your two open questions.
Scope (v1)
Read-only MongoDB connector treating a database as a primary context source: collections → tables, inferred top-level fields → columns, native sampling for enrichment. Context-only, so not SQL- or metric-compilable (more below). One prerequisite refactor lands first.
The dialect (the one correction)
"No
dialect.ts" doesn't quite hold.KtxDialectis doing two jobs and only one is SQL. The catalog and entity-details paths callgetDialectForDriver(snapshot.driver)for reference formatting and type mapping (formatDisplayRef,parseDisplayRef,mapDataType,mapToDimensionType), and that registry is exhaustive over the driver union, so a Mongo snapshot would throw there without an entry.So we're splitting the interface:
KtxDialect(core, every driver incl. mongodb): display/ref formatting + type mapping. Mongo implements this, all trivial, no SQL.KtxSqlDialect extends KtxDialect(SQL drivers only): the query generators. Mongo never implements these, and their only callers (relationship profiling/validation) are already gated onreadOnlySql, so they're unreachable for a Mongo source.Net: Mongo still writes zero SQL, but it ships a small
dialect.tscovering the display/type half. The split is a pure extraction, no behavior change for the existing 7 drivers.Schema inference (kept close to your proposal)
newest-N by
_iddesc as the canonical default,order_byas the correctness fallback for non-ObjectId keys,sample_sizedefault 1000, all as you described. Mechanics:find({}).sort({<key>: -1}).limit(sample_size)withmaxTimeMS, riding the_idindex, so large collections don't stall.KtxSchemaColumnper field:dimensionType: ObjectId/string → string, int/long/double/decimal → number, date → time, bool → boolean.nullable= field missing in some sampled docs, or seen as null.primaryKey=_id.foreignKeys=[](formalForeignKeys: false).mixedand treat as string.Nested fields (your open question)
Keep each top-level field as one column. A sub-document or array becomes a single opaque column with
normalizedType: 'json', the same wayjsonb/STRUCTare modeled today. No dotted-path columns: I checked, and names likeaddress.citybreak relationship name-matching and thetable.columnkeying in the catalog. Flat fields likeuser_idare still picked up by the existing relationship heuristics.Semantic layer (your other open question)
Context-only for v1. Scan, descriptions, and relationship discovery all tolerate a
readOnlySql: falsesource and degrade gracefully (relationship validation just stays in review state instead of running coverage SQL). ButSemanticLayerService.mapDialectfalls back to postgres for unknown drivers and there's no Mongo compiler inktx-sl, so a Mongo source must not be registered as SL-queryable.ktx sqlalready errors cleanly on a non-SQL connection via the capability check. Actual metric compilation against Mongo is a separate, much larger effort, out of scope here.Capabilities
tableSampling,columnSampling,nestedAnalysis,estimatedRowCountstrue;readOnlySql,columnStats,formalForeignKeysfalse. NoexecuteReadOnlyat all: read-only is structural, since the connector only ever issuesfind/listCollections/estimatedDocumentCount/read aggregations and there's no arbitrary-query path.Files
Connector:
packages/cli/src/connectors/mongodb/{connector,dialect,schema-inference,live-database-introspection}.ts. Pulling inference into its own pure module keeps it unit-testable without a client.Wiring: driver union (
scan/types.ts), core dialect factory (dialects.ts), registration (drivers.ts,scopeConfigKey: 'databases'), a dedicatedmongodbConnectionSchemaindriver-schemas.ts,connection-drivers.ts, the setup picker (setup-databases.ts), and themongodbdriver dep. Plus the non-SQL gates:normalizeDriver(local-scan.ts) andsqlAnalysisDialectForDriver(sql.ts). Use the canonicalresolveKtxConfigReferenceforenv:/file:rather than the local copy the SQL connectors carry.Tests + docs
test/connectors/mongodb/: a pureschema-inference.test.ts(the heart: types, nullability, mixed, nested-opaque), aconnector.test.tswith an injected fake client asserting theKtxSchemaSnapshot, adialect.test.ts, adriver-schemasparse case, and an assertion thatktx sqlrejects a Mongo connection. A MongoDB section inprimary-sources.mdx(config,mongodb+srv/TLS/Atlas, features matrix, the sampling explainer). Keep your real-ktx ingestend-to-end check as the acceptance gate.On scope/tier
Worth flagging: this is meaningfully more than the ClickHouse connector. ClickHouse reused the SQL pipeline wholesale; Mongo is the first non-SQL source, so it carries the dialect split, real inference logic, the SL boundary, and the driver gates. Happy to tier it accordingly, just setting expectations before you dig in.
If this all looks right, it's yours. Open to pushback on any of it.
Pintouch commentedon Jun 22, 2026
Hi @andreybavt
Opened #310 for this. 🎉
It follows the v1 scope we aligned on — context-only (not SL-/metric-queryable),
the prerequisite
KtxDialect→KtxDialect+KtxSqlDialectsplit landed as a pureextraction (the 7 SQL drivers only changed their implements clause),
newest-N-by-_id sampling with order_by as the correctness fallback, and
sub-documents/arrays kept as a single opaque json column. The relationship
pipeline takes a nullable SQL dialect so a Mongo scan skips coverage-SQL
validation and leaves candidates in review. ktx sql and ktx sl query are both
refused for a non-SQL connection rather than defaulting to Postgres.
Wired into the driver registry, the connection schema, and the ktx setup picker;
covered by unit tests (schema inference, connector snapshot via a fake client,
dialect, tableScope/empty-scope, view handling, and the SQL/SL refusals) plus a
runnable
examples/mongodb/.Verified end-to-end:
ktx ingestagainst a seeded MongoDB completes with Databaseschema: done — collections → tables (including a view introspected without a
count), AI descriptions, embeddings, and relationships left in review.
Happy to iterate on anything in review. 🙏
feat(connectors): add MongoDB connector (#305) (#310)
chore(release): 0.14.0 [skip ci]