MongoDB's wire protocol
modules/mongo-compat, §M16 Q5
Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.
nucleus server --mongo-compat [addr] (the front end mongo, default
127.0.0.1:27017) speaks MongoDB’s wire protocol, so mongosh and
MongoDB’s drivers work with collections (§8.41) — the same documents,
indexes and transactions SQL and ncp (§10 Documents) see. A module
on the public API (nucleus_sql::ext::documents, the compiler O
uses), so every request is one SQL statement, planned as any.
- Wire:
OP_MSG(opcode 2013; a body and document sequences —insert’sdocuments—;checksumPresentread past,moreToComeanswered with nothing), andOP_QUERYon<db>.$cmdfor the firsthello/isMastera driver sends, answeredOP_REPLY; other opcodes close the connection. 48 MB a message, 16 MiB a document. TLS when the server has it (the first byte a handshake’s, asncp). - Login: SCRAM-SHA-256 by
saslStart/saslContinue(with or withoutskipEmptyExchange) against the server’s own verifiers (§9), the user named in the client’s first message;hellowithsaslSupportedMechsoffers it. Throttled and audited as the other front ends; a user whose password a directory checks is refused here. Every command but the handshake’s needs a login (13). With--no-auth, the session isnucleus’s. - Commands:
find(filter, projection, sort, skip, limit,batchSize,singleBatch) /getMore/killCursors— the result read whole and kept per connection, handed out 101 documents (orbatchSize) and at most 16 MiB a batch;insert— one statement for the batch, and on a failure one by one so an ordered insert keeps the documents before the failing one and an unordered every other (writeErrorswith each index);update(operators, or a replacement;multi;upsert;n,nModified,upserted),delete(limit0 or 1),count;findAndModify(in one transaction: the first match bysort, updated, replaced or removed, the document before ornew;fields);aggregateof the pipelines drivers send for queries andcountDocuments—$matchfirst, then$sort,$skip,$limit,$project, and a last$countor$groupcounting with{$sum: 1}— compiled to a find or a count (other stages168: SQL answers them, §M16);create,drop,listCollections(nameOnly, a filter by name),listDatabases(the database names the connection used — every name reaches the same collections),createIndexes(path indexes,unique, named<collection>_<name>; a key’s direction ignored, text, geospatial and hashed keys67),dropIndexes,listIndexes(_id_), and what a shell asks first (hello,buildInfo— version 7.0.0, wire version 21 —,getParameter,getCmdLineOpts,getLog,hostInfo,connectionStatus,whatsmyuri,ping,endSessions). An unknown command is59. No sessions are offered (hellogives nologicalSessionTimeoutMinutes), so drivers send nolsidand run no transactions or retryable writes here; nucleus’s own drivers have transactions (§11). - Collections: a write makes a collection that is not there
(
CREATE COLLECTION IF NOT EXISTS); a read of one is empty. A document without_idgets an ObjectId, an upsert’s new document too (by$setOnInsert, or for a replacement after its match was tried). - Types: documents travel as BSON (
mongo_compat::bson, its reader and writer the module’s own) and are kept asjsonwith BSON’s other types in Extended JSON (§M15 item 4): ObjectId{"$oid": "<24 hex>"}, a date{"$date": "YYYY-MM-DDTHH:MM:SS.mmmZ"}(years 0 to 9999; else{"$date": {"$numberLong": …}}), decimal128{"$numberDecimal": "…"}(its digits and exponent kept:1.50), binary{"$binary": {"base64": …, "subType": "hh"}}, a regular expression{"$regularExpression": …}, a timestamp, min and max keys, a double that is not finite{"$numberDouble": …}; on the way out the same objects are those types again. A number is anint32when it is a whole number that fits, anint64when it fits that, else adouble— JSON has one number type, so adouble1.0comes back1(anint64past 2^53 keeps its digits)._idcomes first in a document; the other keys injson’s canonical order (§M15 item 3). - Filters: a filter is compiled as
json_filtercompiles it (§8.41), after three rewrites: a regular expression value is{"$regex": …, "$options": …}; a value Extended JSON wraps (an ObjectId, a date) is compared exactly ({"$eq": …}); and$gt/$gte/$lt/$ltewith a date or an ObjectId compare its text ({"at": {"$gt": date}}is{"at.$date": {"$gt": "…Z"}}) — the ISO text and the hex sort as the values do. For that, a filter’s dotted path may hold a part beginning with$after its first (MongoDB refuses such a path; an operator never stands inside one). Errors map to MongoDB’s codes drivers act on:2350511000(DuplicateKey),42P0126,42P0748,40001112(WriteConflict),22023/0A0002(BadValue, the SQLSTATE in the message).
Tested by the module’s tests/wire.rs (a client of its own over a
socket: the legacy hello, a wrong and a right password, every command
above) and by scripts/mongo-smoke.sh in CI — pymongo (CRUD, bulk_write,
Decimal128 and dates round-tripping, ObjectId equality, date ranges,
regular expressions, find in batches, find_one_and_update, a
duplicate key as DuplicateKeyError) and mongosh’s CRUD and queries;
mongosh’s interactive start (show dbs, show collections) was run
by hand.