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_portinsrc/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_CONNdefaults to on. When on, each connection gets its own OS thread with an 8 MB stack running a current-thread tokio runtime;0orfalseturns 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
BufWriterthat 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; testreaper_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
-
flagBitsis parsed. WhenchecksumPresent(bit 0) is set, the trailing 4 bytes are trimmed but the CRC-32C is not verified.moreToComeandexhaustAllowedare 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.updatesanddelete.deletes. An unknown section kind is an error. (source:src/protocol/mongodb/mod.rs,handle_op_msg; teststest_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, includingSCRAM-SHA-1,PLAINandMONGODB-X509, gets code 18 "Unsupported authentication mechanism".hellowithsaslSupportedMechsreturns["SCRAM-SHA-256"]. (unit testhello_advertises_scram_sha_256_when_asked) - GS2 header:
n,,,y,,andp=<type>,,are accepted. The channel binding value in the client-finalc=attribute is not checked against the TLS channel, sop=tls-server-end-pointgives 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 withaudit::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>:
- A Mongo user record stored at
__mongouser__:<db>.<user>, with its own SCRAM verifier (see Users and roles). - The catalog role's stored SCRAM-SHA-256 verifier, via
catalog_scram_credentials. The role must haverolcanlogin, a password, and passwire_access_allowed("mongodb"). - 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 withbincodeat__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 withpwdhidden. (unit testunauthorized_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/isMasterreturnsismaster: true,isWritablePrimary: true,maxBsonObjectSize16777216,maxMessageSizeBytes48000000,maxWriteBatchSize100000,minWireVersion0,maxWireVersion17,logicalSessionTimeoutMinutes30,readOnly: false. WhenSYNERGY_MONGO_REPLSET_HOSTis set it also advertises a single-node replica set (setNamefromSYNERGY_MONGO_REPLSET_NAME, defaultrs0, plussetVersion,hosts,primary,me), which drivers that require a replica set for transactions need. (source:handle_hello; testshello_command,is_master, unit testhello_advertises_logical_sessions) -
buildInforeports version8.0.0andgitVersionsynergydb. (source:handle_buildinfo; testbuild_info) -
explainreturns an emptyqueryPlannerstub; it does not describe the plan that would run. (source:handle_explain) Not verified: no test. -
listDatabasesis filtered to databases the caller may access. (source:handle_listdatabases_filtered; testlist_databases) -
collStatsand the$collStatsstage report approximate sizes (document count times 100 bytes). (source:handle_collstats; testcoll_stats) -
SYNERGY_MONGO_TRACEenables 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
-
findreadsfilter,projection,sort,skipandlimit(int32 or int64). Projection supports inclusion, exclusion,$slice,$elemMatchand the positionalfield.$. A sort with a limit uses a top-k sort (sort_documents_top_k).batchSizeonfindis ignored; the first batch is always at most 101 documents. (source:handle_find,apply_find_projection,sort_documents_top_k; testsfind_with_*, unit testprojection_positional_and_dotted_paths) - Candidate selection: a filter on
_idbecomes point lookups (point_id_key,id_lookup_keys). Otherwiseplan_index_lookuppicks a built secondary index on an equality or$inpredicate. Every candidate is re-checked withmatches_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.getMorehonoursbatchSizeandmaxTimeMS.killCursorsremoves cursors by id. (source:src/protocol/mongodb/cursor.rs,CursorManager;commands.rs,handle_getmore,handle_killcursors; 4 unit tests incursor.rs) - Change streams: writes append to an in-memory
ChangeLogcapped atCHANGE_LOG_CAP(10,000 entries). Anaggregatewhose first stage is$changeStreamreturns a live cursor; each batch carriespostBatchResumeTokenand each event an_idresume token.aggregate: 1watches 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; statusdocs/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,deleteandfindAndModifyoutside a transaction run inrun_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 testsautocommit_write_is_visible_through_mvcc_layer,autocommit_write_not_visible_before_commit,autocommit_insert_many_all_or_nothing_success) - Ordered
insertManystops at the first error and reportswriteErrors, as MongoDB does. (unit testautocommit_insert_many_partial_failure_matches_mongodb) - Writers take per-document key locks (
lock_doc_keys, hashed onto 64 lock stripes) and holdindex_build_lockshared, so an index build sees a stable collection. (source:lock_doc_keys,create_lock_stripes,index_build_lock) - A duplicate
_idor unique-index violation returnsE11000 duplicate key error;bson_codec::error_responsesets code 11000 whenever the message containsE11000, and code 1 otherwise. (testsduplicate_id_error,unique_index_prevents_duplicates)
Multi-document transactions
- A command carrying
autocommit: falsewithlsidandtxnNumberjoins a transaction;startTransaction: trueopens one in MVCCSnapshotIsolationunderMONGO_COMMIT_LOCK. The session key is thelsidhex plustxnNumber. Retryable-write fields alone (lsid,txnNumberwithoutautocommit: false) do not open a transaction. (source:session_txn_key,active_txn,with_txn_state; unit testssession_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).commitTransactionapplies the buffer with onewrite_batch. (unit teststxn_commit_makes_writes_visible_atomically,txn_delete_and_duplicate_semantics_in_buffer) - Errors:
NoSuchTransaction(251) for an unknowntxnNumber;IllegalOperation(20) when there is no storage engine; on a commit conflictWriteConflict(112) witherrorLabels: ["TransientTransactionError"], which drivers retry. (unit testsunknown_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
txnNumberruns 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,dropSearchIndexand the$listSearchIndexesstage. Indexes of typevectorSearchtakevectorfields (path,numDimensions,similarity) andfilterfields. Indexes of typesearch(Atlas full-text) can be created and listed but nothing queries them. -
$vectorSearchmust be the first stage and takesindex,path,queryVector,numCandidates(1 to 10000),limit,filterandexact.$meta: "vectorSearchScore"exposes the score. - Scores:
cosineanddotProductmap to(1 + x) / 2;euclideanto1 / (1 + d²).MAX_DIMSis 8192. - Indexes live in the shared vector service under namespace
__mongo__, key<db>.<coll>/<index>. Errors usemongo_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 (
nullasz, bools asb0/b1, numbers asn<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) -
createIndexesreadskey,name(default: eachfield_directionjoined by_),unique,sparse,backgroundandexpireAfterSeconds. 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; testscreate_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 testunique_index_is_enforced) -
expireAfterSecondsis stored and returned bylistIndexes, 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 callCommandDispatcherdirectly 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,_idkey, 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_COMPRESSEDand all legacy opcodes other thanOP_QUERY; unknown opcodes get no reply. - OP_MSG checksum verification,
moreToComeand 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,getLastErrorand user-defined roles. - Query operators
$text,$where, geospatial,$jsonSchema,$bits*(they match every document). - Stages
$merge,$sample,$geoNear,$search,$redact,$densify,$fill,$documentsand 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.
-
explainoutput beyond an empty stub.