Craticula

MongoDB rendering

A comparison is always a field document with an explicit operator, and the composites map to the matching MongoDB operators. Null inclusion, blank checks, ranges, collation and the escaping of patterns each have one fixed form. The pinned floor is MongoDB 4.2.

the SQL addendum above, of which this is the exact parallel for the other artifact family)

The SQL addendum exists because #1638 found the same IR construct rendered several different ways from identical inputs across a fixture suite seven parallel agents had hand-authored with no compiler to check it. #1643 compiled the Mongo arm of that same suite for the first time and reproduced the finding on the other side: operators/001 spelled eq explicitly while operators/003 spelled it implicitly, all 47 operators/ artifacts were missing SEM-3's mandatory $unset, and three drill-downs were flat where five SQL arms of the same fixtures composed. So the answers are pinned here, once, for the same reason and in the same register — and not as prose under SEM-1..SEM-7, whose snippets this document's own preamble disclaims as illustrative. A normative sentence there would contradict the framing, and that ambiguity is precisely what let operators/001 and operators/003 disagree in the first place.

Each rule below is the form the spec/fixtures/*/expected/mongo.artifact.json files now contain. There is one MongoDB, so unlike the SQL addendum nothing here is "the reference engine's spelling, other engines differ" — every rule is universal, which is also why there is no MongoDialect seam to hang any of it on (BM-1's smell, mirrored: a single-implementation interface). SQL-0 is not SQL-specific and is not restated: a compiled pipeline takes its collection from schema.source and never from the request.

MDB-1. A comparison is a field document holding an explicit operator — including $eq. {"age": {"$gt": 30}}, and {"status": {"$eq": "active"}} rather than MongoDB's implicit {"status": "active"}.

Why, given the two are semantically identical for every value the IR can carry. SEM-2's MongoDB paragraph is the tiebreaker, and it is normative prose rather than a disclaimed snippet: it emits the explicit composed form for neq even though the naive one is correct, "to keep the compiled shape parallel to the SQL and ES forms" and to stay valid in an $expr context, where only {"$eq": [...]} exists at all. A uniform operator table also needs no carve-out, which is SQL-1's "always quote, no second rule" applied to the other backend. The hand-authored suite spelled it both ways in adjacent cases of one category (operators/001 explicit against 003/005/007/046 implicit; all of filter-tree/ explicit against every group-aggregation/ drill-down implicit), which is why it is pinned rather than left to taste; 21 artifacts were re-authored onto this form in #1643.

MDB-2. The composites, and what a tree-level NOT gets that a bare $nor lacks. andNode → $and, orNode → $or, and a tree-level notNode → $nor with the child as its single member, wrapped in the null fan-out below. A single-child composite is not collapsed ({"$and": [x]}), mirroring SQL-2's (x): the tree's own depth is what filter-tree/011-013 pin against SEC-3's budget, and collapsing it would make a boundary fixture indistinguishable from a shallower one.

A tree-level NOT gets the same null fan-out as SQL-2's third bullet, at every notNode at every depth: {"$or": [{"$nor": [<child>]}, {"<field>": null}, ...]}, one {field: null} clause per distinct field referenced in the child subtree, in first-appearance order. $nor alone is not enough, because it returns a null document only when the child fails to match it, and neq, blank, an inner not or an or whose other field matches all do match one (SEM-2). The {field: null} clause is the inclusion SEM-2 requires and not the {field: {$ne: null}} guard its second MongoDB Must-NOT forbids.

MDB-3. SEM-2's null inclusion is an explicit $or with a {field: null} clause. {"$or": [{"name": {"$ne": "Alice"}}, {"name": null}]} — emitted for neq, notContains and notIn alike, and (per MDB-1's reasoning) emitted even though MongoDB's own $ne already matches a missing field. {field: null} covers a stored null and a missing field together, so it is one clause rather than two.

MDB-4. notContains keeps the negation on the operator: {"c": {"$not": {"$regex": …}}}. SQL-3's rule reached by a different route. $nor is this document's rendering of a tree-level notNode (MDB-2), so spelling a single negated comparison that way makes one leaf's negation indistinguishable from a one-child NOT node in the artifact, on top of losing the field-scoped form MongoDB can index. MDB-3's null-inclusive $or still wraps it: $not alone drops missing-field documents.

MDB-5. blank/notBlank are $in/$nin over [null, ""] on a string, and null/{"$ne": null} on every other type. SEM-2 requires notBlank to be blank's compiled negation and never a re-derived condition; MongoDB has an operator-level negation for each arm ($nin for $in, $ne for the implicit equality), so the negation is applied to the very operator the positive arm chose. SQL-7's second question does not arise here: MongoDB stores "" as a value distinct from null, so the field-type half is the whole answer.

MDB-6. inRange is ONE field document carrying both bounds, never an $and of two clauses. {"age": {"$gte": 18, "$lt": 65}}, each bound spelled from its own explicit inclusivity flag (SEM-4). This is the only place in MongoDB's query language where two constraints on one field compose without a composite, and it is available here because inRange is a single rangeComparisonNode — one IR leaf, not an and of two. It is not GRP-5's flattening being readmitted: an AG Grid within-column AND of two conditions is two IR leaves and is an $and (ag-grid-majors/002), and the two look nearly identical on the wire.

MDB-7. The artifact is the bare pipeline array, or the {pipeline, collation} wrapper — the wrapper if and only if a query-level collation is present. MongoDB's collation is an aggregate() command option, not a stage, so it cannot be an element of the pipeline array; spec/fixtures/schemas/mongo-artifact.schema.json admits both shapes and this rule is what chooses between them. A collation is present exactly when some construct resolved to SEM-1's collation mechanism case-insensitively — a user's $eq/$ne/$gt/$gte/$lt/$lte/$in/$nin on a case-insensitive string, or a $sort key on one. $regex never contributes (SEM-1 assigns the substring family the pattern-match mechanism, which carries its own $options: "i"), and neither does any pipeline that computes bucket identity (GRP-2's accepted divergence #3).

MDB-8. SEM-3's bucket names, including the two SEM-3 does not define. SEM-3 pins __<field>NullBucket for an ordinary sort key. A grouping request needs two more names, and they are pinned here because nothing else names them:

Sort keyBucket fieldSorted path
an ordinary field__<field>NullBucketthe field's physical path
a grouped level's group column__groupNullBucket_id
an aggregate output__<output name>NullBucketthe output name

The group key's bucket is named for the role, not for the column, because the column changes per level while the key it lands on (_id) does not. The trio is contiguous — $addFields, $sort, $unset, nothing between them — the bucket key precedes its own field in the $sort document, and the bucket's sign follows nullsPosition independently of the field's direction (1 = nulls last), since the bucket is 1 for null and 0 otherwise.

MDB-9. Where a pipeline carries a collation, a case-sensitive string comparison renders as an $expr; a case-sensitive sort key in that pipeline is a compiler error. MongoDB's collation is query-level: it governs $match, $group and $sort together and has no per-stage form. So a request comparing an insensitive field and a sensitive one — which the five SQL dialects render side by side, each spelling its own mechanism per SQL-6 — has, naively, no MongoDB pipeline that honours both, and the naive rendering silently folds case on the field SC-3 declared sensitive. That is SEM-1's third Must-NOT inverted, and it is a wrong rows bug rather than an ordering one.

The intended escape is the aggregation-expression form: it compares by simple binary comparison, which is why SEM-2's own MongoDB paragraph notes that a case-insensitive comparison inside an $expr has to be spelled with $strcasecmp. That premise is false on MongoDB 7.0, which applies the aggregate's query-level collation to $expr comparisons too (the engine run of dialect-parity/023 showed it); see Accepted divergence #5 below. The $expr form is still what the compiler emits, because it is the one spelling that keeps the sensitive comparison out of the query language and is what the artifacts pin, but it does not hold the field case-sensitive under a collation.

FamilyUnder no collationUnder a collation, on a sensitive field
scalar (eq…lte){"c": {"$eq": v}}{"$expr": {"$eq": ["$c", {"$literal": v}]}}
set (in/notIn), non-empty{"c": {"$in": [...]}} / $nin{"$expr": {"$in": ["$c", [{"$literal": v₁}, …]]}} / {"$expr": {"$not": [{"$in": …}]}}
set, empty list (SEM-8){"c": {"$in": []}} / {"c": {"$nin": []}}unchanged — the constant applies before any collation or $expr choice
inRangeone field document (MDB-6){"$expr": {"$and": [{"$gte": ["$c", {"$literal": a}]}, {"$lt": ["$c", {"$literal": b}]}]}}
substring{"c": {"$regex": …}}unchanged — a collation does not reach a $regex at all
sort key{"c": 1}rejected — see below

Four consequences worth spelling out, because each is a place a port will guess:

The $-as-path rewriting is confined to the aggregation-expression language. The query language performs no such thing — in {"c": {"$eq": "$salary"}} the value is the four-character string, and the only value the query language reinterprets is a BSON regex — so no ordinary field document, $in array, $regex pattern or blank sentinel elsewhere in this addendum needs binding. That asymmetry is the whole reason the requirement is easy to lose: the escape moves a value that was safe into the one place it is not.

Accepted divergence #5 — MongoDB cannot hold a case-sensitive field in the same request as case-insensitive ones. A pipeline that carries a query-level collation (SEM-1 wants one for the case-insensitive field) compares every string under it, a sensitive field's $expr included, and no per-stage or per-expression form exists in the pinned subset. A request that mixes the two sensitivities therefore returns, on MongoDB, rows that match case-insensitively on the field SC-3 declared sensitive: SEM-1's third Must-NOT, accepted here in the same register as GRP-2's divergences #3 and #4. dialect-parity/023 records it as an XEQ-4 allowedDivergence entry for mongo, whose expected holds the rows the engine returns (ab-100 and Ab-100 match AB-100); the six other backends return the exact rows. A host that needs case-sensitive matching on MongoDB keeps that field out of a request that also carries a collation.

Pinned by dialect-parity/023, the suite's only artifact containing an $expr. The $literal binding of a $-prefixed value and the sort refusal are pinned by unit tests alone (MongoPipelineOperatorTests, MongoPipelineSortAndPagingTests) — the sort refusal because there is no artifact for a request that does not compile (exactly as for SQL-7(b)), the binding because the other six backends bind such a value through their own parameter mechanism and would show nothing the existing arms do not already show.

MDB-10. Every stage MongoDB emits is a document, so every name a request can influence needs a collision check. A repeated key in a BSON document is last-wins, not an error, and three of the names in a compiled pipeline are client-influenced: the $sort keys (a grid may send a colId twice in sortModel; since SEM-6's reduction that no longer reaches the compiler, see the first collision), the aggregate output names and hence their buckets (AGG-2 derives them from valueCols[].id), and MDB-8's reserved __groupNullBucket. Each collision is silent and each changes the answer:

The second and third MUST be rejected (the first no longer arises: SEM-6's reduction removes a repeat, and its one exception, a case-insensitive text stable key, gets the synthetic tiebreaker field above). Renaming either side is not an alternative: the emitted bucket name would then depend on what else the request happened to contain, which is a worse oracle than an error. There is no SQL counterpart to any of this — the SQL compiler renders null placement as an inline expression rather than as a named field, and a repeated ORDER BY key is merely redundant on most of them (SQL Server refuses it, error 169, which is the bug SEM-6's reduction prevents).

MDB-11. SEM-7's escape set is "every ASCII character outside [A-Za-z0-9]", and "character" means one ASCII byte. SEM-7 states the rule as "a full backslash-escape of every character outside [A-Za-z0-9]" and leaves character undefined, which is a real ambiguity rather than a pedantic one: a compiler iterating UTF-16 code units inserts a backslash between the two halves of a surrogate pair, producing two lone surrogates — and a JSON writer then replaces each with U+FFFD, so contains "😀" compiles to a pattern matching nothing, silently. Restricting the escape to ASCII answers the question by removing it, at no semantic cost: PCRE2, the engine $regex uses, has no metacharacter above U+007F, so escaping a non-ASCII character can only change the pattern's spelling. A port that reads SEM-7 as "every character" and iterates code points emits a different pattern for the same IR, which is a G4 divergence; this rule is what both ports have to agree on. dialect-parity/020 and /022 pin the ASCII half (50% off (bonus) → 50\%\ off\ \(bonus\)).

MDB-12. The pinned floor is MongoDB 4.2. Two constructs put it there, and both are emitted by essentially every pipeline this compiler produces, so the floor is not conditional on the request:

ConstructIntroducedEmitted by
$unset as an aggregation stage4.2SEM-3's null-bucket trio — i.e. every pipeline, since SEM-6 makes the tiebreaker unconditional
{"$not": {"$regex": …}} in a query4.0.7MDB-4's notContains; earlier servers require the BSON regex type instead of the $regex operator here

Recorded explicitly, in the same register as Oracle's 12.2 floor (SQL-6) and SQLite's 3.30.0 one: both of those are loud failures when unmet, and so is this — an unrecognised pipeline stage is a server error, not a silent difference. A host on 4.0/4.2 that wants $unset avoided would need $project with the buckets excluded, which changes every artifact in the suite and is therefore a different rendering rule rather than a configuration option.

Cross-links. spec/fixtures/schemas/mongo-artifact.schema.json (the two artifact shapes), $defs/andNode, $defs/orNode, $defs/notNode, $defs/unaryOperator, $defs/binaryOperator, $defs/setOperator, $defs/rangeComparisonNode, $defs/sortItem, SEM-1, SEM-2, SEM-3, SEM-4, SEM-6, SEM-7, SEC-4, SEC-5, AGG-1, AGG-2, AGG-6 (already satisfied natively here — $sum returns 0 and the other three return null, so no accumulator changes), GRP-2..GRP-6, and the SQL addendum's SQL-0 (source), SQL-2 (the composite wrap this one parallels) and SQL-3 (the negation-on-the-operator rule MDB-4 reaches independently).