Text-to-query: building natural-language querying over MongoDB and SQL
The full pipeline from a user's question to an executed query and a readable answer — schema cards, constrained generation, validation layers, and result summarisation.
Natural-language querying (NLQ) lets a non-technical user ask a database a question in plain English and get an answer. The naive version — 'hey model, write me the SQL' — demos beautifully and is a liability in production. A real NLQ system is a pipeline with validation and safety at every join.
The pipeline
- Schema card — a compact description of the relevant tables/collections, key fields, and relationships.
- Constrained generation — the model writes a query given the schema and a few examples.
- Validation — parse the query, static-check it, and enforce safety before it touches the database.
- Execution — run it against a read-only connection with limits.
- Summarisation — turn the raw rows into a sentence the user actually asked for.
Schema cards, not the whole schema
Don't dump your entire DDL into the prompt. Hand the model a curated schema card — the tables that matter, the important columns with plain descriptions and synonyms, the relationships, and the gotchas. Better input beats a bigger model here.
SQL and MongoDB are not equally easy
Models write SQL well — it's everywhere in their training data. MongoDB's aggregation pipelines are trickier and models stumble more, so lean harder on examples and tighter validation for document stores. The pipeline is the same; the failure rate isn't.
Validate before you execute
Between generation and execution sits the most important step: parse the query, confirm it's a single read-only statement within limits, and only then run it. This is where the safety and silent-failure work lives — covered in the next two posts.
NLQ isn't 'ask the model for SQL'. It's a pipeline where generation is one step, and validation, safety, and summarisation are the rest.