Skip to content

Add MongoDB connector #305

Closed
Closed

Description

@Pintouch

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":

  1. 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. The KtxScanConnector contract still fits via capability flags — readOnlySql: false, formalForeignKeys: false, nestedAnalysis: true — but ktx sql wouldn't apply to a Mongo connection, and it's worth a maintainer sanity-check that the ingest / relationship-discovery path is happy with a readOnlySql: false source end-to-end before anyone writes much code.
  2. 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 no packages/connector-*). No dialect.ts, since it's not SQL.
  • Add mongodb to the KtxConnectionDriver union (src/context/scan/types.ts), a dedicated connection schema in src/context/project/driver-schemas.ts, and a registration in src/context/connections/drivers.ts (scopeConfigKey: 'databases').
  • Use the official mongodb driver.
  • 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 _id isn't an ObjectId (custom string / UUID keys), "newest" is undefined, so allow naming a field (e.g. createdAt) to order by. Optional; defaults to _id desc.
  • 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

  • mongodb driver registered and type-checks across the registry/union/schema wiring
  • Connects via standard mongodb:// / mongodb+srv:// strings, with credentials through env:NAME or file:/path (same as existing connectors), including TLS / Atlas
  • Selectable database + collection allowlist (the enabled_tables equivalent, database.collection form)
  • Infers a schema by sampling the newest sample_size documents (by _id desc, or order_by), handling nested documents and arrays, with BSON types mapped into ktx's type model and nullable derived from field presence
  • _id treated 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 ingest against 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_by on a real updatedAt is 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

  1. added
    needs-triage
    on Jun 17, 2026
  2. andreybavt commented on Jun 17, 2026

    @andreybavt
    Contributor

    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

  3. Pintouch commented on Jun 17, 2026

    @Pintouch
    ContributorAuthor

    Thanks @andreybavt, don't hesitate if you have any questions / suggestion, I will be glad to work on this 👍

  4. andreybavt commented on Jun 17, 2026

    @andreybavt
    Contributor

    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. KtxDialect is doing two jobs and only one is SQL. The catalog and entity-details paths call getDialectForDriver(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 on readOnlySql, so they're unreachable for a Mongo source.

    Net: Mongo still writes zero SQL, but it ships a small dialect.ts covering 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 _id desc as the canonical default, order_by as the correctness fallback for non-ObjectId keys, sample_size default 1000, all as you described. Mechanics:

    • find({}).sort({<key>: -1}).limit(sample_size) with maxTimeMS, riding the _id index, so large collections don't stall.
    • Per top-level field, union the BSON types seen and count presence. One KtxSchemaColumn per 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).
      • When a field's type varies across docs, mark it mixed and 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 way jsonb/STRUCT are modeled today. No dotted-path columns: I checked, and names like address.city break relationship name-matching and the table.column keying in the catalog. Flat fields like user_id are 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: false source and degrade gracefully (relationship validation just stays in review state instead of running coverage SQL). But SemanticLayerService.mapDialect falls back to postgres for unknown drivers and there's no Mongo compiler in ktx-sl, so a Mongo source must not be registered as SL-queryable. ktx sql already 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, estimatedRowCounts true; readOnlySql, columnStats, formalForeignKeys false. No executeReadOnly at all: read-only is structural, since the connector only ever issues find/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 dedicated mongodbConnectionSchema in driver-schemas.ts, connection-drivers.ts, the setup picker (setup-databases.ts), and the mongodb driver dep. Plus the non-SQL gates: normalizeDriver (local-scan.ts) and sqlAnalysisDialectForDriver (sql.ts). Use the canonical resolveKtxConfigReference for env:/file: rather than the local copy the SQL connectors carry.

    Tests + docs

    test/connectors/mongodb/: a pure schema-inference.test.ts (the heart: types, nullability, mixed, nested-opaque), a connector.test.ts with an injected fake client asserting the KtxSchemaSnapshot, a dialect.test.ts, a driver-schemas parse case, and an assertion that ktx sql rejects a Mongo connection. A MongoDB section in primary-sources.mdx (config, mongodb+srv/TLS/Atlas, features matrix, the sampling explainer). Keep your real-ktx ingest end-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.

  5. added
    enhancement
    area:connectors
    area:context
    reward:eligible
    and removed
    needs-triage
    on Jun 17, 2026
  6. Pintouch commented on Jun 22, 2026

    @Pintouch
    ContributorAuthor

    Hi @andreybavt

    Opened #310 for this. 🎉

    It follows the v1 scope we aligned on — context-only (not SL-/metric-queryable),
    the prerequisite KtxDialect → KtxDialect + KtxSqlDialect split landed as a pure
    extraction (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 ingest against a seeded MongoDB completes with Database
    schema: 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. 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area:connectorsarea:contextenhancementreward:eligible

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions