MongoDB wire implementation reference

This page describes how the MongoDB wire is built: framing, authentication, the command dispatch table, the query, update and aggregation language, the storage layout, errors, limits and tests. For the port, the proof scores, how to connect and how to re-run the differential suites, see the operator page MongoDB. Authentication policy across all wires is in Security.

Code lives in src/protocol/mongodb/: mod.rs (listener, framing), commands.rs (CommandDispatcher and nearly all command logic), bson_codec.rs (BSON encoder and decoder), cursor.rs (cursor manager), users.rs (users and roles) and vector_search.rs (Atlas-style vector search). The document AST (BsonDocument, BsonValue) is in src/query/mql/ast.rs.

The BSON codec is written in this repository. The bson crate 2.9 is an optional dependency behind the mongodb-wire Cargo feature, which is not in default; the wire does not use it, and the only source file that references it is the migration connector src/migrate/source/mongodb.rs (source: Cargo.toml, [features]; src/protocol/mongodb/bson_codec.rs). The crates the wire does use are bincode (document storage), pbkdf2, hmac and sha2 (SCRAM), base64, hex, rand and chrono (source: Cargo.toml; src/protocol/mongodb/commands.rs, imports).

Listener and connection loop

  • The default port is 27017 (mongodb_port in src/config.rs). The server builds the handler with storage, or with TLS when a TLS config exists. TLS is implicit: the socket is wrapped at accept, before the first message header is read. (source: src/config.rs; src/server/mod.rs; src/protocol/mongodb/mod.rs, MongoDBHandler::start)
  • SYNERGYDB_MONGO_THREAD_PER_CONN defaults to on. When on, each connection gets its own OS thread with an 8 MB stack running a current-thread tokio runtime; 0 or false turns it off and connections run as ordinary tasks. (source: src/protocol/mongodb/mod.rs, MongoDBHandler::start) Not verified: no test exercises either mode over TCP.
  • Timeouts come from TimeoutConfig::default(): read 60 s, write 60 s, idle 300 s, connect 30 s. (source: src/protocol/timeout.rs, TimeoutConfig::default)
  • The read buffer starts at 256 KB and grows as needed. Replies go through a 64 KB BufWriter that is flushed before the loop waits for the next message, so a pipelined batch is answered with one write. (source: src/protocol/mongodb/mod.rs, handle_connection)
  • Background tasks: the cursor cleanup task runs every 60 s; the transaction reaper runs every 15 s and aborts transactions idle for more than 60 s. (source: src/protocol/mongodb/mod.rs, MongoDBHandler::start; src/protocol/mongodb/commands.rs, reap_expired_mongo_txns; test reaper_aborts_idle_transactions)

Framing

Message header

Every message starts with the 16-byte standard header: messageLength, requestID, responseTo, opCode, all little-endian i32. A messageLength below 16 closes the connection. BufferLimits::check_message_size applies DEFAULT_MAX_MESSAGE_SIZE (256 MB); a message over the limit gets an error reply (code 10334 MESSAGE_TOO_LARGE, or 2 for an oversized blob) and the connection is closed. (source: src/protocol/mongodb/mod.rs, handle_connection; src/protocol/buffer_limits.rs, BufferLimits::check_message_size)

Opcodes

Opcode Name Handling
2013 OP_MSG Parsed and dispatched. Reply is OP_MSG with flagBits 0 and one kind-0 section.
2004 OP_QUERY Parsed and dispatched. Reply is OP_REPLY.
2012 OP_COMPRESSED Defined, not handled.
1 OP_REPLY, 2001 OP_UPDATE, 2002 OP_INSERT, 2005 OP_GET_MORE, 2006 OP_DELETE, 2007 OP_KILL_CURSORS Legacy Defined, not handled.

Any opcode other than 2013 and 2004 reaches _ => continue: the message is consumed and ignored, and no reply is sent. A client that sends one waits until its own timeout. (source: src/protocol/mongodb/mod.rs, handle_connection)

OP_MSG

  • flagBits is parsed. When checksumPresent (bit 0) is set, the trailing 4 bytes are trimmed but the CRC-32C is not verified. moreToCome and exhaustAllowed are defined but unused: every request gets exactly one reply. (source: src/protocol/mongodb/mod.rs, handle_op_msg)
  • Section kind 0 is the command body. Section kind 1 is a document sequence; each is bounds-checked (section size at least 5 and inside the message, identifier NUL-terminated inside the section, every document size at least 5) and then merged into the body as an array field named by the identifier, which is how drivers send insert.documents, update.updates and delete.deletes. An unknown section kind is an error. (source: src/protocol/mongodb/mod.rs, handle_op_msg; tests test_op_msg_kind1_section_size_overruns_buffer, test_op_msg_kind1_section_size_u32_max, test_op_msg_kind1_identifier_missing_nul_within_bounds)

OP_QUERY

A namespace ending in .$cmd is dispatched as a command, with the database taken from the namespace. Any other namespace is wrapped into a find command with the query document as its filter. The reply is OP_REPLY with responseFlags 0, cursorID 0, startingFrom 0 and numberReturned 1, so a legacy query is answered with a single document holding the command reply. (source: src/protocol/mongodb/mod.rs, handle_op_query)

Compression

Not implemented. OP_COMPRESSED is ignored as above, and hello does not return a compression field, so drivers that negotiate compressors fall back to none. (source: src/protocol/mongodb/mod.rs, handle_connection; src/protocol/mongodb/commands.rs, handle_hello)

BSON codec and type mapping

bson_codec.rs decodes the wire bytes into BsonDocument (an ordered list of (String, BsonValue)) and encodes replies back. Nesting deeper than MAX_BSON_DEPTH (100) is rejected. (source: src/protocol/mongodb/bson_codec.rs, decode_document, MAX_BSON_DEPTH; src/query/mql/ast.rs, BsonValue)

Tag BSON type Decoded to Notes
0x01 double Double(f64)  
0x02 string String  
0x03 document Document  
0x04 array Array Keys are discarded.
0x05 binary Binary { subtype, bytes }  
0x06 undefined Null Lossy: re-encodes as null.
0x07 ObjectId ObjectId([u8; 12])  
0x08 bool Boolean  
0x09 UTC datetime DateTime(i64 ms)  
0x0A null Null  
0x0B regex Regex { pattern, options }  
0x0C DBPointer rejected "Unknown BSON type"
0x0D JavaScript rejected The encoder can emit it.
0x0E Symbol rejected  
0x0F CodeWithScope rejected The encoder can emit it.
0x10 int32 Int32  
0x11 timestamp Timestamp  
0x12 int64 Int64  
0x13 Decimal128 Decimal128([u8; 16]) Raw bytes kept and round-tripped. No arithmetic or comparison semantics.
0xFF / 0x7F MinKey / MaxKey MinKey / MaxKey  

(source: src/protocol/mongodb/bson_codec.rs, decode_value, BsonEncoder::encode_element; tests roundtrip_* in tests/protocol_mongodb.rs)

Comparisons between values of different types follow the BSON type order through bson_type_rank and bson_total_compare; numbers of different widths compare by value. (source: src/protocol/mongodb/commands.rs, bson_type_rank, bson_total_compare; unit test total_compare_orders_across_types)

Authentication

SCRAM-SHA-256

saslStart and saslContinue implement SCRAM-SHA-256 (RFC 7677). (source: src/protocol/mongodb/commands.rs, handle_saslstart, handle_saslcontinue)

  • Mechanism: only SCRAM-SHA-256. Any other mechanism, including SCRAM-SHA-1, PLAIN and MONGODB-X509, gets code 18 "Unsupported authentication mechanism". hello with saslSupportedMechs returns ["SCRAM-SHA-256"]. (unit test hello_advertises_scram_sha_256_when_asked)
  • GS2 header: n,,, y,, and p=<type>,, are accepted. The channel binding value in the client-final c= attribute is not checked against the TLS channel, so p=tls-server-end-point gives no binding guarantee. Not verified: channel binding.
  • The server nonce is the client nonce plus 24 random ASCII letters. The server-final message carries v=<ServerSignature>. Conversation state is per connection. Every attempt is recorded with audit::record_login.
  • Any failure (unknown user, wrong proof, malformed message) is answered "Authentication failed." with code 18, so a client cannot tell an unknown user from a wrong password.

Credential lookup order for <db>.<user>:

  1. A Mongo user record stored at __mongouser__:<db>.<user>, with its own SCRAM verifier (see Users and roles).
  2. The catalog role's stored SCRAM-SHA-256 verifier, via catalog_scram_credentials. The role must have rolcanlogin, a password, and pass wire_access_allowed("mongodb").
  3. Users seeded from the environment when the dispatcher is built.

(source: src/protocol/mongodb/commands.rs, handle_saslstart, catalog_scram_credentials; src/auth/wire_auth.rs, wire_access_allowed)

Environment-seeded users (all optional): MONGODB_ADMIN_USER (default admin) with MONGODB_ADMIN_PASSWORD; SYNERGYDB_SUPERUSER (default synergy) with SYNERGYDB_SUPERUSER_PASSWORD; MONGODB_TENANT_USERS="user:pass:db1,db2;..." for users limited to the listed databases. Seeded verifiers use 15000 PBKDF2 iterations and a 16-byte random salt. (source: src/protocol/mongodb/commands.rs, create_user_credentials, create_user_credentials_with_dbs) A user is seeded only when its password variable is set.

The catalog verifier is written by backfill_password_verifiers on a successful login on any wire, so a role created through SQL becomes usable over Mongo after it has logged in once anywhere that runs the backfill. (source: src/auth/wire_auth.rs, backfill_password_verifiers; unit test successful_login_backfills_missing_wire_verifiers)

Wire access and the failed-login delay

wire_access_allowed("mongodb") passes a superuser or a member of synergy_wire_mongodb or synergy_wire_all. A name that is not in the catalog is allowed, and SYNERGYDB_WIRE_ACCESS=open|off|any turns the check off. The shared failed-login delay (5 free failures, then 200 ms doubling to a 5 s cap, in a 600 s window, keyed by user name) is in wire_auth.rs. (source: src/auth/wire_auth.rs, wire_access_allowed, FREE_AUTH_FAILURES, MAX_AUTH_DELAY; unit test delay_starts_after_free_failures_and_is_capped) Not verified: whether the SCRAM path calls the delay; no Mongo test covers it.

Pre-auth allowlist and database access

Before authentication only these commands run: hello, ismaster, saslstart, saslcontinue, ping, whatsmyuri, buildinfo, getlog, hostinfo, serverstatus, getparameter, replsetgetstatus, top, endsessions, refreshsessions, killsessions, killallsessions, killallsessionsbypattern, listdatabases, connectionstatus. Every other command needs is_authenticated, and database-scoped commands also pass check_database_access(db). A refusal is "not authorized on <db> to execute command <name>" with code 13. (source: src/protocol/mongodb/commands.rs, dispatch_inner, check_database_access, is_authenticated)

Variable Default Effect
MONGODB_ENFORCE_DB_ACCESS on 0, false, no, off, n, f turn per-database checks off. An unrecognised value keeps them on. (unit tests truthy_spellings_enable_and_falsy_disable, unset_or_garbage_stays_enabled)
SYNERGYDB_DEV_INSECURE_AUTH off 1 or true lets unauthenticated clients run every command.

(source: src/protocol/mongodb/commands.rs, enforce_db_access_from_env; src/auth/wire_auth.rs, dev_insecure_auth_enabled)

Users and roles

users.rs implements MongoDB's user commands and built-in roles. (source: src/protocol/mongodb/users.rs; src/protocol/mongodb/commands.rs, handle_user_command)

  • Storage: a MongoUser { user, db, user_id, roles, scram, custom_data } encoded with bincode at __mongouser__:<db>.<user>. A generation counter, re-read at most once a second per connection, carries role changes to connections that are already authenticated.
  • The model is opt-in: a login that has no Mongo user record (a catalog role or an env-seeded user) keeps full access, limited only by the database checks above.
  • Commands: createUser, updateUser, dropUser, dropAllUsersFromDatabase, grantRolesToUser, revokeRolesFromUser, usersInfo, rolesInfo, connectionStatus.
  • Errors: 51003 user already exists, 31 role not found, 11 user not found, 13 Unauthorized. The refusal text renders the command with pwd hidden. (unit test unauthorized_text_hides_password)
Built-in role Scope
read, readWrite, dbAdmin, userAdmin, dbOwner One database
readAnyDatabase, readWriteAnyDatabase, dbAdminAnyDatabase, userAdminAnyDatabase, root, backup, restore, clusterMonitor, clusterManager, clusterAdmin, hostManager admin only

Each command maps to one action (Read, Meta, Write, Ddl, DropDatabase, UserAdmin, Cluster) through action_for. aggregate with $out or $merge counts as Write. A command the table does not know needs Cluster on admin. (source: src/protocol/mongodb/users.rs, action_for; unit tests builtin_roles, aggregate_with_out_is_a_write; commands.rs test roles_limit_what_a_user_runs)

User-defined roles (createRole and the rest of the role commands) are not implemented. The proof run is described in docs/status/2026-11-30-mongo-users-roles.md.

Command dispatch

CommandDispatcher::dispatch_inner takes the first key of the command document, lowercases it, and matches it. Every command is classified as Read, Write or Admin for the audit log (audit_command). (source: src/protocol/mongodb/commands.rs, dispatch_inner, audit_command)

Handled commands

Group Commands
Handshake and diagnostics hello, isMaster/ismaster, ping, whatsmyuri, buildInfo, getLog, replSetGetStatus, serverStatus, getParameter, hostInfo, top, connectionStatus, explain
Databases and collections listDatabases, listCollections, create, drop, dropDatabase, renameCollection (with dropTarget), collStats
Indexes createIndexes, dropIndexes, listIndexes
Search indexes createSearchIndexes, updateSearchIndex, dropSearchIndex
CRUD find, insert, update, delete, findAndModify, count, distinct, aggregate
Cursors getMore, killCursors
Auth saslStart, saslContinue
Sessions endSessions (also aborts that session's open transactions), refreshSessions, killSessions, killAllSessions, killAllSessionsByPattern (these four answer ok: 1 and do nothing)
Transactions commitTransaction, abortTransaction
Users createUser, updateUser, dropUser, dropAllUsersFromDatabase, grantRolesToUser, revokeRolesFromUser, usersInfo, rolesInfo

Any other name returns "no such command: '<name>'" with code 59 and codeName CommandNotFound (source: src/protocol/mongodb/commands.rs, dispatch_inner; test unknown_command).

Notes on specific commands

  • hello / isMaster returns ismaster: true, isWritablePrimary: true, maxBsonObjectSize 16777216, maxMessageSizeBytes 48000000, maxWriteBatchSize 100000, minWireVersion 0, maxWireVersion 17, logicalSessionTimeoutMinutes 30, readOnly: false. When SYNERGY_MONGO_REPLSET_HOST is set it also advertises a single-node replica set (setName from SYNERGY_MONGO_REPLSET_NAME, default rs0, plus setVersion, hosts, primary, me), which drivers that require a replica set for transactions need. (source: handle_hello; tests hello_command, is_master, unit test hello_advertises_logical_sessions)
  • buildInfo reports version 8.0.0 and gitVersion synergydb. (source: handle_buildinfo; test build_info)
  • explain returns an empty queryPlanner stub; it does not describe the plan that would run. (source: handle_explain) Not verified: no test.
  • listDatabases is filtered to databases the caller may access. (source: handle_listdatabases_filtered; test list_databases)
  • collStats and the $collStats stage report approximate sizes (document count times 100 bytes). (source: handle_collstats; test coll_stats)
  • SYNERGY_MONGO_TRACE enables per-command tracing to the log. (source: dispatch_inner)

Not implemented

These names fall through to code 59: getLastError (the test get_last_error only checks that the reply has an ok field, which an error reply also has), bulkWrite (the role table has an entry, but there is no handler), dbStats, collMod, createRole and the other role commands, listCommands, currentOp, killOp, validate, mapReduce, logout, getMore on a tailable capped collection, and all sharding and replication administration commands. (source: src/protocol/mongodb/commands.rs, dispatch_inner)

Reads: find, cursors and change streams

  • find reads filter, projection, sort, skip and limit (int32 or int64). Projection supports inclusion, exclusion, $slice, $elemMatch and the positional field.$. A sort with a limit uses a top-k sort (sort_documents_top_k). batchSize on find is ignored; the first batch is always at most 101 documents. (source: handle_find, apply_find_projection, sort_documents_top_k; tests find_with_*, unit test projection_positional_and_dotted_paths)
  • Candidate selection: a filter on _id becomes point lookups (point_id_key, id_lookup_keys). Otherwise plan_index_lookup picks a built secondary index on an equality or $in predicate. Every candidate is re-checked with matches_filter, so an index only narrows the scan. Without either, the collection prefix is scanned. (source: load_candidate_documents, plan_index_lookup, index_candidate_keys)
  • Cursors live in CursorManager. A cursor expires 10 minutes after it was created, not after its last use, so a slow consumer can lose a cursor it is still reading. getMore honours batchSize and maxTimeMS. killCursors removes cursors by id. (source: src/protocol/mongodb/cursor.rs, CursorManager; commands.rs, handle_getmore, handle_killcursors; 4 unit tests in cursor.rs)
  • Change streams: writes append to an in-memory ChangeLog capped at CHANGE_LOG_CAP (10,000 entries). An aggregate whose first stage is $changeStream returns a live cursor; each batch carries postBatchResumeToken and each event an _id resume token. aggregate: 1 watches the whole database. The log is not persisted, so a resume token from before a restart, or older than the last 10,000 changes, cannot resume. (source: ChangeLog, CHANGE_LOG_CAP, build_change_event, attach_resume_token; status docs/status/2026-11-30-mongo-window-graph-union-txn.md) Not verified: no Rust test resumes a change stream.

Query operators

matches_filter and matches_operator evaluate filters. Dotted paths traverse arrays implicitly, so {"a.b": 1} matches any element of a whose b is 1. (source: src/protocol/mongodb/commands.rs, matches_filter, matches_operator, get_field_values; unit test matches_dotted_path_into_array_of_subdocuments)

Kind Operators
Logical $and, $or, $nor, $not, $expr
Comparison $eq, $ne, $gt, $gte, $lt, $lte (range operators exclude null and missing), $in, $nin
Element $exists, $type (numbers and the aliases double, string, object, array, binData, objectId, bool, date, null, int, timestamp, long, decimal, number)
Evaluation $regex with $options, $mod, $expr
Array $size, $all, $elemMatch

(tests query_*_operator in tests/protocol_mongodb.rs; unit tests cluster1_not_is_honored, cluster1_mod_is_honored, cluster2_range_excludes_null_and_missing, regex_options_case_insensitive, in_and_nin_match_array_field_membership, expr_filter_compares_against_now)

An unknown query operator matches every document (_ => true in matches_operator). $text, $where, $geoWithin, $geoIntersects, $near, $nearSphere, $jsonSchema, $bitsAllSet and the other $bits* operators, and $comment are not implemented and do not raise an error: a filter that uses one returns documents as if that clause were absent. (source: src/protocol/mongodb/commands.rs, matches_operator)

Writes

Update operators

Kind Operators
Field $set, $unset, $inc, $mul, $min, $max, $rename, $currentDate (date or timestamp), $setOnInsert
Array $push (with $each, $position, $sort, $slice), $pull (value or condition), $pullAll, $addToSet (with $each), $pop
Bitwise $bit (and, or, xor)
Positional $, $[], $[<id>] with arrayFilters

A replacement document (no $ keys) replaces the document and keeps _id. A pipeline update (an array) accepts the stages $set/$addFields, $unset, $project, $replaceRoot and $replaceWith. Upserts apply $setOnInsert and the equality fields of the filter. (source: apply_update, apply_pipeline_update, set_field_with_filters, bitwise_operation; tests update_*_operator, replace_one; unit tests upsert_insert_applies_set_on_insert_and_set, current_date_timestamp_type_yields_bson_timestamp)

Write path and locking

  • insert, update, delete and findAndModify outside a transaction run in run_in_implicit_txn: the writes are buffered in an MVCC transaction and committed as one batch, so a reader never sees half of a multi-document write. (unit tests autocommit_write_is_visible_through_mvcc_layer, autocommit_write_not_visible_before_commit, autocommit_insert_many_all_or_nothing_success)
  • Ordered insertMany stops at the first error and reports writeErrors, as MongoDB does. (unit test autocommit_insert_many_partial_failure_matches_mongodb)
  • Writers take per-document key locks (lock_doc_keys, hashed onto 64 lock stripes) and hold index_build_lock shared, so an index build sees a stable collection. (source: lock_doc_keys, create_lock_stripes, index_build_lock)
  • A duplicate _id or unique-index violation returns E11000 duplicate key error; bson_codec::error_response sets code 11000 whenever the message contains E11000, and code 1 otherwise. (tests duplicate_id_error, unique_index_prevents_duplicates)

Multi-document transactions

  • A command carrying autocommit: false with lsid and txnNumber joins a transaction; startTransaction: true opens one in MVCC SnapshotIsolation under MONGO_COMMIT_LOCK. The session key is the lsid hex plus txnNumber. Retryable-write fields alone (lsid, txnNumber without autocommit: false) do not open a transaction. (source: session_txn_key, active_txn, with_txn_state; unit tests session_txn_key_parses_lsid_and_number, retryable_write_fields_do_not_open_a_transaction)
  • Reads inside a transaction overlay its own buffered writes (overlay_txn_writes). commitTransaction applies the buffer with one write_batch. (unit tests txn_commit_makes_writes_visible_atomically, txn_delete_and_duplicate_semantics_in_buffer)
  • Errors: NoSuchTransaction (251) for an unknown txnNumber; IllegalOperation (20) when there is no storage engine; on a commit conflict WriteConflict (112) with errorLabels: ["TransientTransactionError"], which drivers retry. (unit tests unknown_txn_number_is_no_such_transaction, txn_abort_discards_all_writes, end_sessions_aborts_open_transactions)
  • Retryable writes are not deduplicated: a retried write with the same txnNumber runs again. Not verified: no test covers a retried non-idempotent write.

Aggregation

handle_aggregate loads the collection's documents into memory and runs each stage with execute_pipeline_stage. A leading $match on _id narrows the load to point lookups; any other pipeline reads the whole collection. Results are returned through a cursor in batches of 101. There is no spill to disk and no allowDiskUse handling. (source: handle_aggregate, execute_pipeline_stage)

Stages

Stage Notes
$match, $project, $sort, $limit, $skip, $count, $unset, $addFields/$set, $replaceRoot, $sortByCount  
$unwind String form and options form (includeArrayIndex, preserveNullAndEmptyArrays)
$group Accumulators below (execute_group_stage)
$lookup localField/foreignField form, and let/pipeline form (execute_lookup_stage, execute_lookup_pipeline)
$graphLookup maxDepth, depthField, restrictSearchWithMatch
$unionWith Collection or collection plus pipeline
$facet, $bucket, $bucketAuto  
$setWindowFields $rank, $denseRank, $documentNumber, $shift, and accumulators over documents or range windows (window_bounds)
$out Must be last; drops and recreates the target collection
$vectorSearch, $listSearchIndexes, $changeStream, $collStats First stage only

(source: execute_pipeline_stage, execute_graph_lookup_stage, execute_set_window_fields, execute_facet_stage, execute_bucket_stage, execute_bucket_auto_stage; tests aggregate_* in tests/protocol_mongodb.rs; status docs/status/2026-11-30-mongo-window-graph-union-txn.md) The tests in tests/protocol_mongodb.rs cover $match, $group, $sort, $limit, $project, $unwind and a multi-stage pipeline; the other stages are covered only by the differential proof run.

An unknown stage passes documents through unchanged. $merge (counted as a write for authorization but never executed), $replaceWith as a stage, $sample, $geoNear, $search, $searchMeta, $redact, $densify, $fill and $documents are not implemented and raise no error. (source: execute_pipeline_stage)

Accumulators

$sum, $avg, $min, $max, $first, $last, $push, $addToSet, $count, $stdDevPop, $stdDevSamp, $mergeObjects. An unknown accumulator yields null. $min and $max ignore nulls. (source: evaluate_accumulator; unit test cluster6_min_max_ignore_null)

Expression operators

evaluate_expression handles field paths, $$ROOT, $$CURRENT, $$NOW, let variables and these operators; evaluate_extended_operator holds most of them. (source: evaluate_expression, evaluate_extended_operator, eval_arithmetic)

Kind Operators
Arithmetic $add, $subtract, $multiply, $divide, $mod, $abs, $ceil, $floor, $sqrt, $exp, $ln, $pow, $round, $trunc
Comparison and boolean $eq, $ne, $gt, $gte, $lt, $lte, $cmp, $and, $or, $not
Conditional $cond, $ifNull, $switch
String $concat, $toLower, $toUpper, $strLenCP, $strLenBytes, $substr, $substrCP, $substrBytes, $split, $trim, $ltrim, $rtrim, $indexOfCP, $indexOfBytes, $strcasecmp
Array $arrayElemAt, $size, $in, $filter, $map, $reduce, $concatArrays, $reverseArray, $slice, $indexOfArray, $range, $first, $last, $sortArray, and the array forms of $max, $min, $avg, $sum
Set $setUnion, $setIntersection, $setDifference, $setEquals, $setIsSubset, $anyElementTrue, $allElementsTrue
Object $mergeObjects, $objectToArray, $arrayToObject
Type $type, $isNumber, $isArray, $toDate, $toLong, $toInt, $toDouble, $toBool, $toString
Date $dateToString
Other $literal, $let, $meta (vectorSearchScore)

Arithmetic is n-ary and keeps MongoDB's result types (int32 plus int32 stays int32 unless it overflows, any double makes a double). (unit test add_and_multiply_take_every_operand_and_keep_integer_types; status docs/status/2026-11-30-mongo-nary-arithmetic.md)

An unknown expression operator is returned unchanged as a literal document. Not implemented: date part operators ($year, $month, $dayOfWeek and the rest), $dateFromString, $dateAdd, $dateDiff, $dateTrunc, $regexMatch, $regexFind, $replaceOne, $replaceAll, $convert, $getField, $setField, $zip, $function, $accumulator. (source: evaluate_extended_operator)

Vector search

vector_search.rs implements the Atlas Vector Search surface. (source: src/protocol/mongodb/vector_search.rs; 3 unit tests in that file; status docs/status/2026-11-24-es-mongo-vector-search.md)

  • Index commands: createSearchIndexes, updateSearchIndex, dropSearchIndex and the $listSearchIndexes stage. Indexes of type vectorSearch take vector fields (path, numDimensions, similarity) and filter fields. Indexes of type search (Atlas full-text) can be created and listed but nothing queries them.
  • $vectorSearch must be the first stage and takes index, path, queryVector, numCandidates (1 to 10000), limit, filter and exact. $meta: "vectorSearchScore" exposes the score.
  • Scores: cosine and dotProduct map to (1 + x) / 2; euclidean to 1 / (1 + d²). MAX_DIMS is 8192.
  • Indexes live in the shared vector service under namespace __mongo__, key <db>.<coll>/<index>. Errors use mongo_error(code, codeName).

Storage mapping

Item Key Value
Document mongodb:<db>:<coll>:<idkey> bincode of the internal BsonDocument (not raw BSON)
Collection metadata mongodb:<db>:<coll>:__collection_metadata__ Options
Index definitions mongodb_meta:<db>:<coll>:indexes List of index specs
_id re-key marker mongodb_meta:<db>:<coll>:idkeys2 Present once the collection uses the current _id key format
Secondary index entry mongoidx:<db>:<coll>:<index>:<encoded value>\0<idkey> Empty
Index built marker mongoidxbuilt:<db>:<coll>:<index> Present once the backfill finished
Mongo user __mongouser__:<db>.<user> bincode MongoUser

(source: src/protocol/mongodb/commands.rs, storage_key_with_db, index_entry_keys, index_built_key, ensure_id_keys_current; src/protocol/mongodb/users.rs)

_id key encoding

bson_value_to_string turns _id into the key suffix so that distinct BSON values never share a key and equal numbers do:

_id type Key text
String Raw text, unless it looks like a number or a 24-hex ObjectId, in which case it gets the tag s
Int32, Int64, Double The plain number; 1, 1.0 and NumberLong(1) share a key, as MongoDB treats them as equal
ObjectId 24 hex characters
Bool, null, date, binary, array, document Tags b, n, d, x, a, o

ensure_id_keys_current re-keys an older collection once and then writes the idkeys2 marker. (source: bson_value_to_string, string_key_needs_tag, ensure_id_keys_current; unit test id_types_do_not_collide; status docs/status/2026-11-27-mongo-id-types.md)

Secondary indexes

  • Index values are encoded by equality class (null as z, bools as b0/b1, numbers as n<canonical>, strings and the rest by their own encoding), with % escaping of : and %. Values that cannot be encoded go under ?. An array field writes one entry per element (multikey). (source: index_encode, index_values_of, maintain_index_entries)
  • createIndexes reads key, name (default: each field_direction joined by _), unique, sparse, background and expireAfterSeconds. A new index is backfilled (build_index_entries) and marked built; until then the planner does not use it. (source: handle_createindexes, ensure_indexes_built; tests create_indexes, create_compound_index, list_indexes, drop_index)
  • Uniqueness is enforced only for single-field built indexes (check_unique_indexes). A unique compound index is accepted but not enforced. (unit test unique_index_is_enforced)
  • expireAfterSeconds is stored and returned by listIndexes, but there is no TTL reaper: no document ever expires.
  • Without a storage engine the dispatcher keeps collections in an in-memory map; this mode is used by unit tests.

Error replies

Error replies have ok: 0, errmsg, code and usually codeName.

Code codeName When
1 InternalError Any error whose message does not match a more specific case
2 BadValue Malformed arguments, oversized blob
11 UserNotFound User commands
13 Unauthorized Missing authentication, database access, or role check
18 AuthenticationFailed SCRAM failure or unsupported mechanism
20 IllegalOperation Transaction with no storage engine
31 RoleNotFound User commands
59 CommandNotFound Unknown command
112 WriteConflict Commit conflict, with TransientTransactionError label
251 NoSuchTransaction Unknown or aborted txnNumber
10334 BSONObjectTooLarge Message over the size limit
11000 DuplicateKey _id or unique index violation
51003   User already exists

(source: src/protocol/mongodb/bson_codec.rs, error_response; src/protocol/mongodb/commands.rs; src/protocol/mongodb/users.rs; tests unknown_command, insert_missing_collection_name, find_with_invalid_filter_type, update_missing_updates_field, delete_missing_deletes_field, aggregate_missing_pipeline)

Limits and configuration

Setting Default Source
mongodb_port 27017 src/config.rs
Max message size 256 MB (DEFAULT_MAX_MESSAGE_SIZE) src/protocol/buffer_limits.rs
Advertised maxBsonObjectSize / maxMessageSizeBytes / maxWriteBatchSize 16777216 / 48000000 / 100000 handle_hello
BSON nesting depth 100 bson_codec.rs, MAX_BSON_DEPTH
First batch / aggregate batch 101 documents handle_find, handle_aggregate
Cursor lifetime 10 min from creation cursor.rs
Transaction idle limit 60 s (reaper every 15 s) reap_expired_mongo_txns
Change log 10,000 entries in memory CHANGE_LOG_CAP
Vector dimensions 8192 vector_search.rs, MAX_DIMS
SYNERGYDB_MONGO_THREAD_PER_CONN on mod.rs
MONGODB_ENFORCE_DB_ACCESS on enforce_db_access_from_env
MONGODB_ADMIN_USER, MONGODB_ADMIN_PASSWORD, SYNERGYDB_SUPERUSER, SYNERGYDB_SUPERUSER_PASSWORD, MONGODB_TENANT_USERS unset (user names admin, synergy) create_user_credentials
SYNERGY_MONGO_REPLSET_HOST, SYNERGY_MONGO_REPLSET_NAME unset, rs0 handle_hello
SYNERGY_MONGO_TRACE off dispatch_inner
SYNERGYDB_DEV_INSECURE_AUTH off src/auth/wire_auth.rs

Test coverage

  • tests/protocol_mongodb.rs: 94 tests. They call CommandDispatcher directly with BSON documents; none opens a TCP connection, so framing, TLS and SCRAM over the wire are not covered here. They cover inserts, finds and projection, update operators ($set, $inc, $unset, $push, $pull, $rename), deletes, findAndModify, the query operators, sort, skip and limit, count, distinct, seven aggregation tests, indexes including uniqueness, collection commands, handshake commands, BSON round-trips for 13 types, error replies, and persistence through the storage engine.
  • Unit tests: commands.rs (39, including the transaction, _id key, n-ary arithmetic and role tests named above), bson_codec.rs (9), cursor.rs (4), users.rs (3), mod.rs (4, OP_MSG section bounds), vector_search.rs (3).
  • Differential proofs against real MongoDB are listed on the operator page. The proof harness log for the operation corpus (docs/proof/2026-11-30/proof-pack-a3232c9/logs/mongo-operation-corpus.txt) records that it connected with no authentication, so those runs did not exercise SCRAM.

Not implemented

  • OP_COMPRESSED and all legacy opcodes other than OP_QUERY; unknown opcodes get no reply.
  • OP_MSG checksum verification, moreToCome and exhaust cursors.
  • SCRAM-SHA-1, X.509, LDAP, Kerberos and OIDC authentication; channel binding.
  • The commands listed under Not implemented in the dispatch section, including bulkWrite, dbStats, collMod, getLastError and user-defined roles.
  • Query operators $text, $where, geospatial, $jsonSchema, $bits* (they match every document).
  • Stages $merge, $sample, $geoNear, $search, $redact, $densify, $fill, $documents and others (they pass through).
  • Decimal128 arithmetic and comparison.
  • TTL expiry, unique compound indexes, text and geospatial indexes, collations, capped collections and tailable cursors.
  • Retryable-write deduplication; persisted change streams.
  • explain output beyond an empty stub.