MongoDB query language

Two separate pieces of code accept MongoDB commands, filters, update documents and aggregation pipelines:

  MongoDB wire evaluator Engine-side MQL analyzer
Code src/protocol/mongodb/commands.rs src/query/mql/
Reached from MongoDB listener (drivers, mongosh) SQL wires through text detection; HTTP Studio with protocol: mongodb
Translation Native: documents loaded into memory and matched, updated and aggregated in Rust MqlParser to MqlCommand, MqlPlanner to LogicalPlan, QueryEngine::execute_plan
Storage KV records mongodb:<db>:<coll>:<idkey> Relational table named after the collection
Coverage Wide; differential-tested against MongoDB Narrow; parser-level tests only

(source: src/protocol/mongodb/commands.rs, dispatch_inner, storage_key_with_db; src/query/mql/mod.rs, MqlAnalyzer::parse_command; src/query/mql/planner.rs, MqlPlanner::plan)

The two do not share data: a collection written over the MongoDB wire is a set of key-value records, while the engine-side analyzer reads and writes a SQL table of the same name (source: src/protocol/mongodb/commands.rs, storage_key_with_db; src/query/mql/planner.rs, plan_find, plan_insert). CommandDispatcher holds an MqlAnalyzer field and resets it when the database changes, but never calls it (source: src/protocol/mongodb/commands.rs, CommandDispatcher).

1. MongoDB wire evaluator

The wire evaluates every command itself. The command table, query operators, update operators, aggregation stages, accumulators, expression operators, vector search, storage keys and tests are documented in MongoDB wire implementation reference; this section gives the translation summary only.

  • dispatch_inner lowercases the first key of the command document and calls a handler; an unknown command is error 59 CommandNotFound (source: src/protocol/mongodb/commands.rs, dispatch_inner).
  • Reads choose candidates by _id point lookup or a built secondary index on an equality or $in predicate, else scan the collection prefix; every candidate is re-checked with matches_filter (source: src/protocol/mongodb/commands.rs, load_candidate_documents, plan_index_lookup, matches_filter).
  • aggregate loads the collection into memory and runs each stage with execute_pipeline_stage (source: src/protocol/mongodb/commands.rs, handle_aggregate, execute_pipeline_stage).
  • No LogicalPlan is built, so the SQL optimizer, plan cache and SQL row-level security do not apply.

Three silent fallbacks matter when porting queries: an unknown query operator matches every document, an unknown pipeline stage passes documents through, and an unknown expression operator is returned as a literal document (source: src/protocol/mongodb/commands.rs, matches_operator, execute_pipeline_stage, evaluate_extended_operator; see the reference).

Tested by tests/protocol_mongodb.rs and the unit tests under src/protocol/mongodb/ (source: the reference, Test coverage).

2. Engine-side MQL analyzer

2.1 Entry points

  • SQL wires. QueryEngine::detect_language classifies text that starts with { or db. as MQL and calls MqlAnalyzer::parse_command with default database test (source: src/query/engine.rs, QueryEngine::detect_language, QueryEngine::parse_query; src/query/mql/mod.rs, MqlAnalyzer::new). The parser expects a command document such as {"find": "users", "filter": {"age": {"$gt": 30}}}; shell syntax like db.users.find({}) fails to parse on this path (source: src/query/mql/parser.rs, MqlParser::parse_command).
  • HTTP Studio. POST /api/query with protocol: mongodb converts shell syntax to a command document with convert_mongo_shell_to_json, then calls MqlAnalyzer::parse and execute_plan (source: src/protocol/http/routes.rs, execute_query_for_studio).
  • POST /api/v1/query refuses "language": "mql" with "MQL queries should use the MongoDB endpoint" (source: src/protocol/http/routes.rs, execute_query).

Not wired: MqlAnalyzer::parse_document, which builds a command from an already decoded document, has no caller outside src/query/mql/ (source: src/query/mql/mod.rs, MqlAnalyzer::parse_document).

2.2 Lexer

The lexer reads a JSON-like syntax with unquoted keys, single or double quotes, comments, regex literals, and the shell constructors ObjectId(...), ISODate(...), Date(...), new Date(...), Timestamp(...), BinData(...), NumberLong(...), NumberInt(...), NumberDecimal(...), plus null, true and false (source: src/query/mql/lexer.rs). Tested by test_objectid, test_date, test_regex, test_comments and six other tests in src/query/mql/lexer.rs.

2.3 Commands

Command LogicalPlan
find Scan of the collection, then Filter, Project, Sort, Limit (with skip as offset)
insert Insert; columns are the union of keys across the documents, missing keys are NULL
update Update with assignments from the update document (first entry of updates only); multi and upsert are ignored; a pipeline update is refused with "Pipeline updates not yet supported"
delete Delete with the filter; limit is ignored
findAndModify With remove, Delete with limit 1; otherwise Update
aggregate Pipeline stages applied in order over a Scan (table below)
count Aggregate with Count over a filtered Scan
distinct Distinct ON (key) over a filtered Scan; no projection to the key column
create CreateTable with _id TEXT PRIMARY KEY and _doc JSONB, if not exists
drop DropTable, if exists
createIndexes CreateIndex on the collection table
dropIndexes DropIndex named <collection>_<index>
listCollections Scan of pg_class where relkind = 'r'
listDatabases Scan of pg_database
ping, hello, isMaster, ismaster, getMore, killCursors Empty
anything else Parse error "Unknown command"

(source: src/query/mql/parser.rs, MqlParser::parse_command; src/query/mql/planner.rs, MqlPlanner::plan, plan_find, plan_insert, plan_update, plan_delete, plan_aggregate, plan_count, plan_distinct, plan_create_index)

create makes a two-column _id/_doc table, but insert writes one column per document key, so documents inserted into a collection made by create need columns that the table does not have (source: src/query/mql/planner.rs, MqlPlanner::plan, plan_insert). Not verified: no test runs create followed by insert through the engine.

2.4 Filters

Top-level keys $and, $or and $nor combine sub-filters; $expr is converted with the expression rules in 2.7. A field with a plain value is an equality (source: src/query/mql/planner.rs, filter_to_expr, field_condition_to_expr).

Operator Engine expression
$eq, $ne, $gt, $gte, $lt, $lte Comparison
$in, $nin IN / NOT IN list; the value must be an array
$exists IS NOT NULL for true, IS NULL for false
$regex LIKE, after regex_to_like_pattern turns .* into %, . into _, and drops ^ and $ anchors
$not NOT of the inner condition
$type, $all, $elemMatch, $size, $mod, $text, $where, $jsonSchema Literal TRUE, so the clause matches every row

(source: src/query/mql/planner.rs, operator_to_expr, regex_to_like_pattern)

$not builds its inner condition with an empty field name and does not substitute the real field afterwards, although the comment says it does (source: src/query/mql/planner.rs, operator_to_expr). Not verified: no test uses $not on this path.

A regex is matched as LIKE, so character classes, alternation and quantifiers other than .* are compared literally (source: src/query/mql/planner.rs, regex_to_like_pattern).

2.5 Update modifiers

Modifier Assignment
$set, $setOnInsert field = value ($setOnInsert is treated as $set)
$unset field = NULL
$inc, $mul field = field + v, field = field * v
$min, $max LEAST(field, v), GREATEST(field, v)
$currentDate NOW()
$rename New field gets the old value; old field set to NULL
$push, $addToSet ARRAY_APPEND, ARRAY_ADD_UNIQUE
$pop ARRAY_REMOVE_FIRST for -1, ARRAY_REMOVE_LAST for 1
$pull, $pullAll ARRAY_REMOVE, ARRAY_REMOVE_ALL
$bit Bitwise and, or, xor

A replacement document (no $ keys) becomes one assignment per field (source: src/query/mql/planner.rs, plan_update, modifiers_to_assignments). Not verified: no test checks that the array functions named above exist in the SQL engine's function table.

2.6 Aggregation stages

Stage LogicalPlan
$match Filter
$project Project
$group Aggregate with the _id expressions as group keys
$sort, $limit Sort, Limit
$skip Limit with an offset and no limit
$lookup Left Join on localField = <as>.foreignField
$unwind Project of * plus unnest(field)
$addFields, $set Project of * plus the new expressions
$count Aggregate with Count
$sortByCount Group, count into _count, sort descending
$sample ORDER BY RANDOM() with a limit
$out, $replaceRoot, $replaceWith, $facet Parsed; input returned unchanged

(source: src/query/mql/planner.rs, apply_pipeline_stage; src/query/mql/parser.rs, parse_pipeline_stage)

Accumulators: $sum, $avg, $min, $max, $first, $last, $push (array aggregate), $addToSet (distinct array aggregate), $count. Any other accumulator, such as $stdDevPop, is dropped from the output (source: src/query/mql/planner.rs, accumulators_to_exprs).

2.7 Expressions

"$field" becomes a column reference. $add, $subtract, $multiply, $divide and $mod become binary operators over an array of operands; $concat uses the first two operands only; $cond becomes CASE; $ifNull becomes COALESCE. A literal sub-document becomes a string of its Rust debug form (source: src/query/mql/planner.rs, bson_to_expr, operator_expression_to_expr, binary_array_expr, cond_expr, if_null_expr).

2.8 Tests

  • src/query/mql/mod.rs: test_parse_find_query, test_parse_aggregate_query, test_parse_insert, test_parse_update, test_parse_delete, test_parse_hello.
  • src/query/mql/parser.rs: 6 tests on documents, arrays and find, aggregate and insert commands.
  • src/query/mql/planner.rs: test_plan_simple_find, test_plan_insert.
  • src/query/mql/lexer.rs (10) and src/query/mql/ast.rs (3).

These tests stop at the LogicalPlan. Not verified: no test executes an MQL command through QueryEngine.