Skip to content

Mongo queries: keep whole documents in a JSON column - #114577

Open
alexey-milovidov wants to merge 286 commits into
masterfrom
mongo-queries-json-storage
Open

alexey-milovidov wants to merge 286 commits into
masterfrom
mongo-queries-json-storage

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 13, 2026 •

Copy link
Copy Markdown
Member

Related: #68493
Related: #58394

Adds two ways to run MongoDB queries against ClickHouse:

  • a wire protocol endpoint (mongo_port), so MongoDB drivers and tools such as pymongo and mongosh can connect to ClickHouse as if it were a MongoDB server;
  • a query dialect (SET dialect = 'mongo'), so MongoDB shell syntax can be sent over the usual ClickHouse interfaces.

This continues @scanhex12's #68493 - it holds all of its commits - and changes how a collection is stored, which is what the review of that pull request asked for (#68493 (comment)): a collection the endpoint creates keeps whole documents in one JSON column rather than a column inferred per field of the first document.

CREATE TABLE db.users (`_id` String, `json` JSON) ENGINE = MergeTree ORDER BY `_id`

The document goes into the JSON column, whose paths are its fields, and its object id into the _id column, which is the primary key. A document may then hold a field that no document before it had, may leave out a field another one has, and $exists answers what it means. A table that was created in ClickHouse keeps its own columns, and a field of a query names the column of the same name there, so an application can also be pointed at a table that already holds the data.

A read of the documents as they are stored selects them next to the types of their paths, so a date reads back as a BSON date and an integer as an int32/int64 of its width.

The integration tests of test_mongo_protocol say what each shape answers now - a collection of documents where that is what is tested, a table created in ClickHouse where the test is about a column - and 75/75 of them pass.

This is a draft because a few things of a document collection are an explicit error rather than an answer: an update of it, an index over a path, the mongo dialect over it, the element-wise match of an array by equality or $in, $unwind of a path, and the accumulators that read a number. They are the next commits; every one of them is listed in docs/en/interfaces/mongo.md and pinned by a test in the meantime.

Changelog category (leave one):

  • Experimental Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Added a MongoDB-compatible wire protocol endpoint (the mongo_port server setting) and a MongoDB query dialect (SET dialect = 'mongo') for basic collection operations. A collection the endpoint creates keeps whole documents in a JSON column.


Workflow [PR]
Sync PR [sync-upstream/pr/114577]

…`$regex` expectation

`03214_mongo_queries` matched `c2` against the `LIKE` pattern `%a%`, which only selected
the values containing an `a` because `$regex` was translated into `like`. As a regular
expression the same pattern matches nothing, so the query now spells it as `a`.

`test_unknown_operator_is_an_error` used `$in`, which is supported now; it uses `$mod`
instead, which is not.
Mongo reads a number or a boolean in a projection as whether to keep the field and only a
document or a `$` prefixed value as an expression, so `{"a": 1.0}` includes `a` rather than
projecting the constant `1.0` onto it.
SingleStore Kai is the other MongoDB compatibility layer over a SQL engine, and it publishes the
list of commands, operators and stages it supports. Taking that list as the checklist turned up
what an application written against it would hit here, and three defects of what was already
implemented.

Filters gained `$exists`, `$mod`, `$size`, `$all`, `$elemMatch`, `$expr` - which uses the
aggregation expression language and so can compare two fields of the same document - the bitwise
`$bitsAllSet`, `$bitsAnySet`, `$bitsAllClear` and `$bitsAnyClear`, and `$comment`. A table has a
fixed set of columns, so `$exists` asks whether the field holds a value rather than whether it is
declared: `{"$exists": false}` is a `NULL`.

Pipelines gained `$unset`, `$sortByCount`, `$sample`, `$replaceRoot`/`$replaceWith` and `$unwind`.
`$unwind` is an `ARRAY JOIN`, with `preserveNullAndEmptyArrays` choosing between an inner and a
left one and `includeArrayIndex` adding the position of the element counted from zero.

Expressions gained the string, array, set and date operators of the Kai list, `$map` and `$filter`
with the element bound to a lambda parameter of the name they ask for, and `$firstN`/`$lastN`.
`$dayOfWeek` was wrong: it numbers the days from Sunday, which is the mode 3 of `toDayOfWeek` and
not the mode 0 it was translated into.

`update` gained `$unset`, `$mul`, `$min`, `$max`, `$rename`, `$currentDate`, `$push`, `$addToSet`,
`$pop`, `$pull` and `$pullAll`. Every operator of a statement now contributes to the same list of
assignments; before, a statement holding two of them produced `and(<assignments>, <assignments>)`
instead of one `ALTER TABLE ... UPDATE`.

`updateMany` was not executable through the dialect at all: the parser produced a bare
`ASTAlterCommand`, which is not a statement, and only the wire handler wrapped it into an
`ALTER TABLE`. It produces the whole statement now, and the handler executes it as it is.

A `SET` was not parsable in this dialect, so a session that switched to it could never switch back
out - `SET dialect = 'clickhouse'` failed with a syntax error about a missing parenthesis. It is
parsed by the ClickHouse parser now, the way PRQL and Kusto do it, in the client and in the server
alike. A failed parse also used to throw a `SYNTAX_ERROR` with an empty message.

The commands `distinct`, `dropDatabase`, `ping`, `buildInfo`, `connectionStatus`, `killCursors` and
`endSessions` are answered rather than rejected; a driver sends them on connect and on close.
…ct_unsupported`

The test runner fails a test whose standard output matches `Exception`, so
`04664_mongo_dialect_unsupported` - which prints the error message of every
unsupported operator - failed in `Fast test` with `having exception in stdout`
although its output was exactly its reference. The `DB::Exception: ` prefix is
dropped from the printed message; the error code and the message itself, which
is what the test asserts, stay.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=68493&sha=853d6c15635b838914f4d87bd6b7d0ca2d91e39a&name_0=PR&name_1=Fast%20test
A filter names a nested field either as a subdocument, `{"profile" : {"name" :
"x"}}`, or as a dotted path, `{"profile.name" : "x"}`, while the column is
always the dotted path. `modifyFilter` was meant to normalize the first form
into the second, but it kept the name of the field that holds the subdocument
and only rewrote the names inside it, so `{"profile" : {"name" : "x"}}` reached
the parser as `{"profile" : {"profile.name" : "x"}}` and failed with
`The filter operator 'profile.name' is not supported`. A subdocument is now
replaced by the fields it names, and it is told apart from a document of
operators by its member names.

The `update` command did not normalize its filter at all, unlike `find` and
`delete`, so it also could not be given a filter on a nested field.
`createCollection` has no document to infer a schema from, so it created a
table with a single `JSON` column named `json`, but `insert` flattens a document
into a column per field and inserts it with `input_format_skip_unknown_fields =
0`. The first insert into an explicitly created collection therefore always
failed: `db.createCollection("c")` followed by `insert_many([{"x" : 1}])`
rejected `x` as an unknown field of a table whose only column is `json`.

The placeholder is now given the schema of the first inserted document, so a
collection created explicitly ends up with the same columns as one created by
the insert itself. The columns are altered rather than the table recreated: an
`ALTER` of an empty table only rewrites the metadata, while a `DROP` would throw
away a table that may hold something else. A placeholder that is not empty is an
error instead.
`test_create_collection` now inserts into and reads back the collection it
creates, `test_update_by_a_nested_field` covers a filter on a nested field in
both its forms, and `test_unknown_operator_is_an_error` uses `$typo` instead of
`$mod`: `$mod` became a supported operator in `853d6c15635`, so the test no
longer had an unsupported operator to reject and failed with
`DID NOT RAISE`. All 31 tests of `test_mongo_protocol` pass locally.
FerretDB runs its integration suite against a real MongoDB server and asserts that both answer
alike, so its cases are a statement of what MongoDB does at the edges. Eight of them the obvious
translation gets wrong.

`$all` of an empty array matched every document. Mongo matches none, while the ClickHouse `hasAll`
of an empty array holds for every row - the one case here that returned a wrong result rather than
an unhelpful error.

`$rename` of a field onto itself wrote the value to the column and then reset the same column to
its default, so the field was silently emptied. It is an error now, as it is in Mongo. Two
operators of one statement that write the same field - `{"$set": {"a": ...}, "$inc": {"a": ...}}` -
reached the mutation as two assignments to one column and came back as
`MULTIPLE_ASSIGNMENTS_TO_COLUMN`, which names neither the field nor the reason.

`$limit`, `$skip` and the size of `$sample` rejected a whole number written as a double. That is
what a driver sends for a number without a fractional part, and what Extended JSON does in its
relaxed form, so `{"$limit": 5.0}` failed where Mongo accepts it. A bit position had the same
problem. `$limit: 0` is an error in Mongo and returned an empty result here.

An empty `$and`, `$or` or `$nor` failed with a syntax error that said nothing, and a `$mod` by zero
failed while the query ran rather than while it was read.

`04665_mongo_dialect_edge_cases` covers the cases that now answer, and the arguments Mongo rejects
are in `04664_mongo_dialect_unsupported`.
…o-queries

# Conflicts:
#	tests/queries/0_stateless/04664_mongo_dialect_unsupported.reference
Replaying the filter literals of the FerretDB test suite through the dialect crashed the server
four times over. Two causes, both reachable from any Mongo client:

`ParserMongoFilter` asserted that what it was given is a document and then walked its members
regardless. An assertion does not hold in a release build, so `{"$or": [{"a": 1}, true]}` - a
boolean where a filter belongs, which FerretDB checks because MongoDB rejects it - iterated the
members of a value that has none. The tree that came out had a hole in it, and the server followed
the null pointer the moment anything walked the query.

An empty field name built an identifier without a name, which is the same kind of tree, so
`{"": "foo"}` crashed as well.

A filter that holds no condition at all is now rejected where it is combined with others rather
than pushed into the list as a null: `{"$or": [{}, {}]}` reached `or()` with two null arguments.

All four are kept in `04664_mongo_dialect_unsupported` as a regression test.
FerretDB runs the cases of its integration suite against a real MongoDB server and asserts both
answer alike, so its inputs are the shapes a MongoDB client actually sends - including the ones a
MongoDB server rejects, which are the interesting ones for a translation. Replaying them is what
found the segmentation fault of the previous commit.

975 of those inputs are vendored as `data_mongo/ferretdb_query_corpus.txt`, which carries the
attribution and the list of changes made to the original work: the `bson.D` literals of the table
driven cases were converted into Extended JSON and wrapped into a `find`, an `updateMany` or an
`aggregate`, the duplicates were dropped, and the literals holding a BSON type a column cannot
store were left out.

The assertions of the suite are not vendored with them. What it asserts is what a MongoDB server
answers, and a collection whose fields are columns of one type each cannot always answer the same,
so a reference of results would record this implementation's answers rather than MongoDB's and
would have to be regenerated for every operator added. The test asserts only what stays true as
more of MongoDB is implemented: the whole corpus is consumed, every exception carries a code and a
message, no query produces a logical error, and the server is still there afterwards.

The corpus runs as a single multi query, which takes about ten seconds.
The test runner passes `--send_logs_level=error` to every client, so the server streams each
rejected query back to the client as a log entry, and every such entry ends with
`Stack trace (when copying this message, always include the lines below):`. The corpus test reads
the client's standard error looking for the shapes a crash leaves there, one of which is
`Stack trace` - so the 335 ordinary rejections of the corpus were reported as a crash and the
`no crash` line disappeared from the output. There was no crash: the whole corpus was consumed,
the server answered afterwards, and its log holds no fault.

The client now writes the server's log to `/dev/null`, so what is examined is the client's own
output and nothing else, and the crash shapes are matched case sensitively and with their
punctuation - `Assertion .+ failed` is how the C library reports one, while a case insensitive
`Assertion.*failed` also matches the name of the error code `CANNOT_PARSE_INPUT_ASSERTION_FAILED`,
which is an ordinary rejection.

Checked that each of the four shapes - `Segmentation fault`, a sanitizer report, a C library
assertion, and `Stack trace:` - is still detected, and that neither the streamed log entry nor
`CANNOT_PARSE_INPUT_ASSERTION_FAILED` is.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=68493&sha=8ade9533439363919dc58f11a538a0f9fd69ec64&name_0=PR&name_1=Fast%20test
…from a value

Two of the findings of the review that were still open, both reachable by any client.

`db.t.deleteMany({})` - which deletes every document - crashed the server. An empty filter leaves
`ParserMongoFilter` with no condition to hand back, and `ASTDeleteQuery` has no notion of a delete
without a predicate: `formatQueryImpl` and `InterpreterDeleteQuery::execute` both walk it
unconditionally, so the null one was followed. It now says `WHERE 1`, which is what the update path
already did with an empty filter, and what the delete means.

The `.limit(...)` and `.sort(...)` suffixes of a `find` were searched for as plain text over the
whole query, so a document holding the pattern in a value of its own was read as one:
`db.t.find({"name": ".limit(1)"})` looks for a name and asks for no limit, but it came back with a
`LIMIT 1` built from the user's data. The text handed to the parser also reaches to the end of
everything the client sent, so a `find` without a limit took the limit of a later query of the same
multi query. Only the text that follows the argument list of this `find`, and stops at its
terminator, is searched now.

`MongoQueryKeyNameExtractor` also read past the end of the query text: it walked to the closing
parenthesis without a bound, and the count of its search underflowed for a text shorter than the
pattern. Both are bounded now, and an unclosed suffix is reported rather than followed.

Added `04692_mongo_dialect_empty_filter_and_suffixes`.
…ield path

`parseMongoAccumulator` kept a pointer into the temporary AST returned by
`parseMongoAggregateExpression` after the statement destroyed it, so every
`{"$sum": <literal>}` accumulator read freed memory - found by ASan in
04659/04661 and by the wire-protocol integration tests, where it aborted the
server. The expression is now held alive across the check.

A field path of `$` alone produced an empty `ASTIdentifier`, whose
constructor asserts, so the FerretDB corpus queries like
`db.corpus.aggregate([{"$group":{"_id":"$"}}])` aborted the client and the
server in debug builds. It is a `BAD_ARGUMENTS` exception now.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=68493&sha=3d6d5f52174579229ec87574ec8281396d796cec&name_0=PR
PR: #68493
`{"$unwind": "$"}` produced an empty `ASTIdentifier` the same way as an
empty field path in an expression, aborting debug builds on the corpus test.

`$sortByCount` sorted only by the count, so groups with equal counts came
back in an arbitrary order and 04662 was flaky; the group key is now a
secondary sort key.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=68493&sha=3d6d5f52174579229ec87574ec8281396d796cec&name_0=PR
PR: #68493
The wire `find` silently ignored the `skip` option, so driver pagination
returned the first page again. The dialect now takes a `.skip(...)` suffix,
which becomes an `OFFSET`, and the wire handler forwards the option.

PR: #68493
…4-bit count

The wire `count` counted the whole table whatever the command said: the
`query` filter now takes the same path as the filter of a `find`, and the
`limit` and `skip` bounds are lowered into the query instead of being
ignored. The reply is no longer narrowed to `int32`, which both overflowed
and made `std::stoi` throw above 2^31 rows.

PR: #68493
…s on insert

A value outside the 32-bit range emitted the unregistered type name `long`,
so the very first insert of such a document failed to create the collection;
it is `Int64` now. A BSON-only scalar arrives as an Extended JSON wrapper
object such as `{"$date": ...}` or `{"$oid": "..."}`, which the flattening
descended into, turning one field into bogus `<field>.$date` columns:
`$date`, `$oid` and `$numberDecimal` are now mapped onto `DateTime64`,
`String` and `Decimal128` columns, and the other BSON types are rejected
explicitly.

PR: #68493
The replies are rebuilt from the output of `FORMAT JSON`, so their types
depended on the JSON output settings of the authenticated user's profile:
with `output_format_json_quote_64bit_integers` an `Int64` column came back
as a BSON string. The executor now forces the settings that decide the shape
of that output.

PR: #68493
…`distinct`

A `$match` stage uses the query syntax, but only `find`/`delete`/`update`
normalized subdocument paths, so `aggregate([{"$match": {"profile":
{"name": "alpha"}}}])` - and the `query` of a `distinct`, which lowers
through `$match` - failed with `The filter operator 'name' is not
supported`. The pipeline serialization now rewrites `$match` filters the
same way as the filter of a `find`.

`distinct` also returns its values in ascending order now, as MongoDB does;
a `GROUP BY` alone left the order arbitrary.

PR: #68493
…go_dialect`

The dialect was live in every build that has rapidjson, unlike `kusto` and
`prql`, which stay behind explicit experimental settings. `dialect =
'mongo'` now requires `allow_experimental_mongo_dialect`, exactly like the
adjacent dialects. The wire protocol stays gated by the explicit `mongo_port`
server configuration, which is opt-in on its own.

PR: #68493
An omitted field of a later document is stored as the default value of its
column, so on an inferred collection `{"$exists": false}` cannot tell such
a document apart from one holding the default explicitly - the schema
section says so now. Also documents `skip`, the `count` options and the
`allow_experimental_mongo_dialect` setting.

PR: #68493
`find` pagination with `skip`, `count` with a `query` filter and the
`limit`/`skip` bounds, an insert of a BSON `int64` and of dates, the
explicit rejection of a BSON type with no column counterpart, a `$match`
on a subdocument (directly and through the `query` of a `distinct`), and
the controlled error for `$` as a field path.

PR: #68493
The FerretDB corpus queries `{"$unset":""}` and `{"$unset":[""]}` put an empty
string into `makeAsterisk`, and the `ASTIdentifier` constructor fails its assertion on an
empty name, which aborts a debug or sanitizer client running the Mongo dialect
(`04666_mongo_dialect_ferretdb_corpus` in the stateless runs of
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=68493&sha=89c981dff3daab298aece805b076133f44c73351&name_0=PR).
An empty field name is now `BAD_ARGUMENTS` in `$unset`, in the flag form of a projection
stage, and in `expandMongoProjectedField`, which covers `$project`, `$set` and the
document form of a group key.
The test pushed the rows of a `UNION ALL` into an array with `$push` and read its elements
0 and 1, but the branches of a union may arrive in any order, so the test was flaky
(amd_debug flaky check at
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=68493&sha=89c981dff3daab298aece805b076133f44c73351&name_0=PR).
The `$group` now uses the order-independent `$min` and `$max`; `$push` and
`$arrayElemAt` keep their coverage in 04661 and 04663.
The dialect always moved only the first argument into the select parser, so
`db.t.find({}, {"name": 1})` silently dropped the projection and returned whole rows,
and `db.t.find()` dereferenced the beginning of an empty argument list. A `find` now
takes an optional filter and an optional projection - the projection becomes the same
`$projection` member the wire protocol injects - and every other operation checks its
arity instead of reading past its arguments.

The projection parser itself now covers the forms MongoDB defines: an exclusion
`{"x": 0}` becomes `* EXCEPT (x)` instead of an empty select list, a boolean flag works
like a numeric one, an empty projection document asks for the whole document, mixing
inclusion with exclusion is an error, and an empty field name is an error rather than an
assertion failure.
…inserted documents

`executeSelectIntoCursor` rebuilt each reply document from the text of a `FORMAT JSON`
result, so a driver read back literal dotted keys instead of the nested documents it
inserted, and strings instead of dates. The cursor replies of `find` and `aggregate`, and
the `values` of a `distinct`, are now encoded from the column types of the result: a
`DateTime`/`DateTime64`/`Date` column becomes a BSON date, an integer column an
`int32`/`int64` of its width, a `Bool` a boolean, an `Array`/`Tuple`/`Map` recurses
element by element, and the dotted name of a column - the way the dialect maps a nested
field - is regrouped into the nested document it names. A column whose type says no more
than the JSON itself (`JSON`, `Dynamic`) keeps its structural conversion.

`QueryExecutor` pins `date_time_output_format` alongside the JSON output settings it
already pinned, because the dates of the result are parsed back by the encoder.

The normalization of `$match` filters on the wire path now also recurses into the
pipeline of a `$unionWith`, whose stages use the same query syntax as the outer ones.
{"$setIntersection", "arrayIntersect"},
{"$range", "range"},
{"$concat", "concat"},
{"$divide", "divide"},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve fractional quotients in decimal $divide

Mongo's $divide returns a decimal quotient when either operand is decimal, but native divide keeps the fixed scale of the decimal operand. For {$divide: [{$numberDecimal: "1"}, 2]}, the constant becomes Decimal128(0) and DecimalUtils::binaryOpResult keeps scale 0, so the result is 0 instead of 0.5. Likewise, 1.00 / 8 becomes 0.12 instead of 0.125. This silently changes valid aggregation results under the default settings.

Use a decimal lowering that preserves the fractional quotient, or reject decimal division until it can be represented faithfully. Add a regression whose quotient needs more fractional digits than the operands. See MongoDB's decimal-result contract.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 Not fixed in this pass; documented in e108cfd807d1 (limitations of mongo.mdx). The dialect does not know the operand types when it translates, and ClickHouse has no division that is decimal for Decimal operands and a double for the others: divideDecimal refuses non-decimals, and Decimal / Float64 is a Float64. A faithful lowering needs either the types at translation time or a new function, so I'm leaving this thread open. As a workaround, the docs say to give the dividend the scale the quotient needs.

alexey-milovidov and others added 3 commits November 8, 2026 11:54
- Read the collection and database names of a command up to the length of the BSON string, so a
  zero byte in them reaches the check of the characters instead of cutting the name there:
  `{drop: "important\0junk"}` addressed `important`.
- Answer only the handshake commands (`isMaster`, `ismaster`, `hello`, also wrapped in `$query`)
  to a `<db>.$cmd` namespace over `OP_QUERY`, and refuse anything else instead of answering it
  with a successful handshake.
- A document that is an element of an `Array(JSON)` has no types of its paths in
  `JSONAllPathsWithTypes`, so its dates are told by their text: the `JSON` type infers a date
  from every string of the shapes it writes them in, so such a string is a date.
- Refuse a `$unionWith` whose arms return a field as values of different BSON kinds (a boolean
  and a number, for instance): the common type of the `UNION ALL` converts one of them.
- Integration tests for all of them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- `$trim`, `$ltrim` and `$rtrim` trim the whitespace code points of Mongo with a regular
  expression: `trimBoth` trims only the ASCII space, and with a set of characters it trims bytes,
  which would cut a multi-byte character apart.
- `$setUnion`, `$setDifference` and `$setEquals` keep `null` as an element of a set:
  `arrayDistinct` leaves it out, so the elements are wrapped into tuples around it.
- `$toDate` of a decimal truncates its text, as `$toLong` does, rather than rounding it through a
  `Float64` into the next millisecond.
- The select of a `find` sets `prefer_column_name_to_alias = 1`, so a projection that computes a
  field under the name of a column does not change what the filter and the sort read.
- The selects of a `find` and a pipeline set `sql_compatible_division_for_integers = 0`, so
  `$divide` of two integers is a double whatever the profile of the user says.
- The filter of a delete is a child of `ASTDeleteQuery`, so `max_ast_elements` counts it.
- `$add` counts the size of the copies it makes of its terms before it makes them.
- Document the remaining differences: a decimal quotient keeps the scale of the dividend, a wide
  integer inside a `Variant` or a `Dynamic` reads back as a double, and a union of fields of
  different kinds is refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
const int key_length = static_cast<int>(key.size());
if (value.IsString())
{
if (auto milliseconds = tryParseJSONDate(std::string_view(value.GetString(), value.GetStringLength())))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Blocker] Preserve stored JSON path types when encoding BSON

A JSON value can contain a date-shaped String: for example, create t(j JSON(at String)) ENGINE = Memory and insert {"j":{"at":"2020-01-01"}} through SQL. A wire find reaches this branch through appendTypedValue and returns j.at as a BSON date instead of the stored string. Ordinary JSON populated with input_format_try_infer_dates = 0 and input_format_try_infer_datetimes = 0 has the same problem. The assumption that these strings cannot exist is therefore false even for supported, existing ClickHouse tables.

Decode using the actual path types, including JSON values nested in arrays, rather than inferring them again from the serialized text. Add a wire regression containing a real date and a date-shaped string side by side. This is a source trace; I did not run a local server.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 Not changed in this pass. Decoding by the stored path types needs the encoder to read the JSON column with its typed paths (JSONAllPathsWithTypes, or the column itself) rather than the serialized text, including inside arrays. That is a rework of appendTypedValue that I could not build and verify here. Leaving it open.

alexey-milovidov and others added 3 commits November 11, 2026 00:09
…re a field

A variable `$$x` of `$map` and `$filter` was translated into the lambda
parameter `__mongo_variable_x`, so a field path `$__mongo_variable_x` in the
body was captured by it: `{$map: {input: "$a", as: "x", in: {$multiply:
["$$x", "$__mongo_variable_x"]}}}` multiplied the element by itself. The
prefix only moved the collision of `$$x` with `$x`.

A field path `$<path>` is translated into the identifier `<path>`, which
never starts with `$` (a text starting with `$$` is a variable), so the
variable is now the lambda parameter `$$x`, and the parameters that the
translation of `$setDifference`, `$anyElementTrue`, `$allElementsTrue`, the
set operators and the `$addToSet` update operator bind themselves are
`$mongo_element` instead of `__mongo_element`, which a field could be named
and be captured by in `$setDifference` and `$addToSet`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Pass `--mutations_sync 2` to the `mongo` dialect client like `05397` does, so
that the `SELECT` after `updateMany` sees the update.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 3 commits November 12, 2026 08:18
…he input table

`find({}, {_id: 0, json: 1}).sort({a: 1})` was translated to an `ORDER BY json.a`
that the projected `json` alias could capture, ordering by the paths of the projected
document rather than of the stored one. The keys of the `ORDER BY` and `LIMIT BY`
that are not names of the select list are now qualified with the input table, like
the select list and the filter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A projection of a whole subdocument does not read it back from a document
collection, so the projected `json` is computed with `$cond` instead, with an
`a` that goes the other way than the stored `a`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
}
}

auto path = make_intrusive<ASTIdentifier>(std::move(parts));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ Blocker — preserve object-valued fields when resolving document paths

For an endpoint-created document {_id: "x", profile: {name: "alice"}}, this helper emits json.profile, which is NULL: the stored leaf is profile.name, while the parent object requires the JSON subtree representation. Consequently, delete_many({"profile": {"$exists": false}}) becomes a delete with isNull(json.profile) and deletes this document even though profile exists. A projection of profile also returns null instead of the object, as the latest reply on the alias-scope thread notes.

Resolve logical fields through both their scalar and object representations at this shared boundary, preserving the distinction from an absent field. Cover a parent-object projection and both $exists values on present-object, scalar, and absent paths, including a delete that must leave the object-bearing document intact. This is a source trace; I could not run a local server.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 Partly fixed in a047ac8bbd1e. On a document collection, isNull/isNotNull of a field (the lowering of $exists) and the equality with null now also check the subobject: isNull(json.p) AND empty(JSONAllPaths(json.^p)), and the opposite for isNotNull. A field that holds an object is therefore present: $exists: false no longer matches it, and delete_many keeps that document. Checked with clickhouse local that json.^p (and json.^p.q for dotted fields) is empty exactly for scalar and absent paths. Not yet done: a projection of a parent object ({profile: 1}) still returns null. Returning the object needs the encoder to accept a JSON subobject or a Dynamic value in the same result column. I am leaving this thread open for that part.

Comment on lines +827 to +830
if (name == "$eq")
return makeASTFunction("isNotDistinctFrom", std::move(left), std::move(right));
if (name == "$ne")
return makeASTFunction("not", makeASTFunction("isNotDistinctFrom", std::move(left), std::move(right)));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ Blocker — compare contained numeric values for $eq and $ne

For an endpoint-created document {a: 1}, the stored path holds Dynamic(Int64), while the positive literal is normalized to UInt64. isNotDistinctFrom(json.a, 1) takes the generic Dynamic comparison path, which compares the contained type names before the values, and returns false; $ne therefore returns true. In particular, delete_many({"$expr": {"$ne": ["$a", 1]}}) deletes a document whose numeric value equals 1.

This is separate from the existing cross-BSON-type coercion finding: both values here are the same Mongo numeric value. Preserve null-aware equality while comparing non-null contained numbers by value, and cover projected equality plus a $expr delete that must preserve the row. The author independently confirmed the equality failure in the latest alias-scope reply; this is a source trace without a local server run.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 Not changed yet. Switching $eq/$ne to equals with explicit null handling would compare a Dynamic by its contained value, but it also makes ClickHouse convert a String alternative to a number, which can throw for a document holding "abc". Doing this safely needs per-type bracketing, the same design question as the open BSON-type-comparison thread above. Leaving this thread open so both can be decided together.

Comment on lines +143 to +146
else if (name == "$inc")
assignments.push_back(makeAssignment(column, makeASTFunction("plus", field(), parseUpdateValue(it->value, name, false))));
else if (name == "$mul")
assignments.push_back(makeAssignment(column, makeASTFunction("multiply", field(), parseUpdateValue(it->value, name, false))));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ Blocker — validate numeric operands before arithmetic updates

parseUpdateValue also accepts null and booleans, so passing documents_are_values = false does not establish the numeric requirement described above. For an existing table t(id Int64, x Nullable(Int64)) holding (1, 5), update_many({"id": 1}, {"$inc": {"x": null}}) becomes x = plus(x, NULL), stores NULL, and is acknowledged. Mongo rejects the nonnumeric operand before changing data. $mul has the same problem; incrementing an existing null by 1 instead succeeds unchanged where Mongo requires an exception.

Validate numeric operands, including numeric Extended JSON wrappers, and guard nonnumeric/null existing values before applying the arithmetic. Add focused stateless cases proving invalid operands and existing null values raise an exception without changing the row. This is a source trace; I could not run a local server.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 Partly fixed in a047ac8bbd1e. $inc and $mul now take only a JSON number or a numeric Extended JSON wrapper ($numberInt/$numberLong/$numberDouble/$numberDecimal). null, booleans, strings and arrays are refused with BAD_ARGUMENTS before any mutation is issued. Not changed: an existing null value still yields null. Refusing it per row would need a throwIf in the mutation expression, and on MergeTree that leaves a mutation that fails and is retried forever, not a refused update. That is worse than the current behaviour, so it needs a separate design (for example, a check query before the mutation). The regression test is still to come, because the server build did not finish here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 The regression test that was still owed here is added in ba9174361061: 05844_mongo_dialect_arithmetic_update_operands checks that $inc / $mul with null, a boolean, a string, an array or a non-numeric wrapper is an error that leaves the row unchanged, and that a number and a $numberLong are applied. The other half is unchanged and still open: an existing null value stays null after $inc, because refusing it per row needs a check before the mutation rather than a throwIf inside it.

alexey-milovidov and others added 5 commits November 14, 2026 23:45
…es, mutation division, row-type guards, `$dateTrunc` and object-valued fields

- A dialect insert refuses an empty subdocument, as the wire insert does, instead of silently
  dropping the field.
- `$inc` and `$mul` require a numeric operand (a JSON number or a numeric Extended JSON wrapper):
  `plus(x, NULL)` would store `NULL` where Mongo refuses the update.
- `DELETE` and `ALTER TABLE ... UPDATE` produced by the dialect carry
  `SETTINGS sql_compatible_division_for_integers = 0`, so `normalizeDivision` keeps `$divide` of
  a `$expr` filter a floating-point division, as the selects of `find` and `aggregate` already do.
- The guards of `$size` and `$toDecimal` check the type the value holds in each row
  (`makeRowType`) rather than `toTypeName` of the column, which is `Dynamic` for a path of a stored
  document and `Nullable(...)` for a nullable column.
- `$dateTrunc` returns the instant of the boundary in the requested timezone (`toDateTime64` with
  the timezone) rather than a `Date`, which the encoder reads as UTC midnight.
- On a document collection, `isNull` / `isNotNull` of a field and the equality with `null` also
  look at the subobject `json.^<field>`: the path of a field that holds an object is `NULL`, so
  `$exists: false` matched, and a delete removed, a document whose field is an object.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master moved the interface documentation pages under
`docs/concepts/features/connect-to-clickhouse/`. The MongoDB interface page now
lives next to the MySQL and PostgreSQL pages in
`protocols/compatibility/mongo.mdx`, with a slug that follows the new layout,
and is listed in the "Compatibility protocols" navigation group.
Master enabled `modernize-use-nodiscard` in `.clang-tidy`, so the `arm_tidy`
build failed on the const member functions added by this PR. The attributes
were added with `clang-tidy --fix` restricted to that check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`a047ac8bbd1e` made `$dateTrunc` return the instant of the boundary in the
requested time zone (`toDateTime64(..., 3, <timezone>)`) instead of a `Date`,
and made `$inc` refuse a non-numeric operand with its own message. The
references of `04659`, `04661`, `05227` (the truncated dates now print as
`DateTime64(3)`) and `04839` (the new `$inc` message) are updated to the
output of the Fast test:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114577&sha=a047ac8bbd1e9be0e76075aa6ac2f97c81d00ddf&name_0=PR&name_1=Fast%20test
#114577

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 This pass (e275f54e1482..a47ab4f6b4df):

  • Merged master, which had moved the interface docs under docs/concepts/features/connect-to-clickhouse/. The MongoDB page is now protocols/compatibility/mongo.mdx, next to the MySQL and PostgreSQL pages, and it is listed in the "Compatibility protocols" group. The default_session_user conflict in ServerSettings.cpp keeps master's text plus the MongoDB saslStart clause.
  • arm_tidy: master turned on modernize-use-nodiscard. ba73f53d6e63 adds [[nodiscard]] to the getters the check flags. I ran clang-tidy with that check on all 41 Mongo translation units and found nothing else, and all of them pass -fsyntax-only.
  • Fast test: a47ab4f6b4df updates the references of 04659, 04661, 05227 and 04839. The new output is the intended result of a047ac8bbd1e: $dateTrunc now returns a DateTime64(3) instant in the requested time zone, and $inc with a non-numeric operand gets its own error.

Still open: the regression tests promised in the replies about empty subdocuments in dialect inserts, $divide in mutations under both values of sql_compatible_division_for_integers, the $size/$toDecimal guards, and $inc with null. The host is too loaded to finish a server build, so I could not produce their references. The other open threads are design questions for a maintainer: BSON type bracketing in comparisons (and $eq on Dynamic), $regexFind without a match, integer overflow promotion, decimal $divide, wide integers in Variant/Dynamic, decoding JSON by its stored path types, the shared construction budget, and returning an object-valued field from a projection.

Comment thread src/Parsers/Mongo/MongoConstants.cpp Resolved
alexey-milovidov and others added 6 commits November 21, 2026 23:55
`quoteString`, `backQuoteIfNeed` and `convertMongoExtendedJSONWrappersDeep`
take a `std::string_view`, so wrapping a `std::string_view` constant into a
`String` only to pass it there is a redundant conversion that clang-tidy
rejects.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114577&sha=a47ab4f6b4df8a04d16f467aabbdf6288e0bcf86&name_0=PR&name_1=Build%20%28arm_tidy%2C%203%2F4%29
PR: #114577

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…d documents

`convertMongoExtendedJSONWrapper` implemented only `$oid`, `$numberDecimal`
and `$date`, so a `$numberInt`, `$numberLong` or `$numberDouble` nested in an
embedded document - an element of an `Array(JSON)` in an insert, the document
of `$push` / `$addToSet`, the argument of `$literal` - was refused with
`NOT_IMPLEMENTED`, while the same wrapper worked as a direct value.

The numeric wrappers are now converted there with the same parsing and range
validation as in `tryParseMongoConstant`. A non-finite `$numberDouble` stays
an error inside a document, because JSON has no spelling for it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The check itself was added earlier (`parseArithmeticOperand`); this is the
regression test that was still owed for it: a `null`, a boolean, a string, an
array or a non-numeric wrapper is an error and leaves the row unchanged, while
a number and a numeric Extended JSON wrapper are applied.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
if (!bson_doc_)
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Trying to construct a Mongo document from a null bson");
doc_size = bson_doc_->len;
document = String(reinterpret_cast<const char *>(bson_get_data(bson_doc_)), doc_size);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Blocker] Keep BSON allocations owned across throwing C++ operations

This constructor takes ownership of bson_doc_ and then allocates document. If that allocation throws, construction never completes, so Document's destructor does not run and the BSON allocation leaks. The JSON constructor has the same issue at line 34, and getJSON leaks its libbson buffer if the String construction throws before bson_free. This is reachable through MEMORY_LIMIT_EXCEEDED when min_allocation_size_to_throw_on_memory_limit is enabled, as well as through allocation failure; repeated failed requests retain memory precisely when the server is under pressure.

Keep the BSON member and temporary JSON buffer in RAII owners. Also keep ownership through reply insertion: calls such as Insert.cpp:497, result.emplace_back(bson_doc_holder.release()), release the pointer before vector growth or this constructor can throw. Move an already-owned Document into the vector instead, and guard cursor row documents while their fields are encoded.

This branch was successfully deployed

1 active deployment
staging - docs — 88823be6 Deployed Nov 24, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... pr-experimental Experimental Feature submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants