Database Manual / Reference

MongoDB Wire ProtocolMongoDB 有线协议

Note

This MongoDB Wire Protocol Specification is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 United States License. You may not use or adapt this material for any commercial purpose, such as to create a commercial database or database-as-a-service offering.本MongoDB有线协议规范根据知识共享署名-非商业性相同方式共享3.0美国许可证获得许可。您不得将此材料用于任何商业目的,例如创建商业数据库或数据库即服务产品。

Introduction介绍

The MongoDB Wire Protocol is a simple socket-based, request-response style protocol. Clients communicate with the database server through a regular TCP/IP socket.MongoDB Wire协议是一种简单的基于套接字的请求-响应式协议。客户端通过常规TCP/IP套接字与数据库服务器通信。

TCP/IP SocketTCP/IP套接字

Clients should connect to the database with a regular TCP/IP socket.客户端应使用常规TCP/IP套接字连接到数据库。

Port

The default port number for mongod and mongos instances is 27017. The port number for mongod and mongos is configurable and may vary.

Byte Ordering字节序

All integers in the MongoDB wire protocol use little-endian byte order: that is, least-significant byte first.

Messages Types and Formats

MongoDB uses the OP_MSG opcode for both client requests and database replies. There are several message formats used in older versions of MongoDB which have been deprecated in favor of OP_MSG.

Note

This page uses a C-like struct to describe the message structure.

The types used in this document, such as int32 and cstring, are the same as those defined in the BSON specification.

Standard Message Header标准消息头

In general, each message consists of a standard message header followed by request-specific data. The standard message header is structured as follows:

struct MsgHeader {
int32 messageLength; // total message size, including this
int32 requestID; // identifier for this message
int32 responseTo; // requestID from the original request
// (used in responses from the database)
int32 opCode; // message type
}
Field字段Description描述
messageLengthThe total size of the message in bytes. This total includes the 4 bytes that holds the message length.消息的总大小(字节)。这个总数包括保存消息长度的4个字节。
requestIDA client or database-generated identifier that uniquely identifies the message.客户端或数据库生成的唯一标识消息的标识符。
responseToThe requestID taken from the messages from the client.从客户端的消息中获取的requestID
opCodeType of message. See Opcodes for details.消息类型。详见操作码

Opcodes操作码

MongoDB uses these opCode values:MongoDB使用这些opCode值:

Opcode Name操作码名称Value价值Comment注释
OP_COMPRESSED2012Wraps other opcodes using compression使用压缩来包装其他操作码
OP_MSG2013Send a message using the standard format. Used for both client requests and database replies.使用标准格式发送消息。用于客户端请求和数据库回复。
OP_REPLY
Deprecated in MongoDB 5.0. Removed in MongoDB 5.1.
1Reply to a client request. responseTo is set.
OP_UPDATE
Deprecated in MongoDB 5.0. Removed in MongoDB 5.1.
2001Update document.更新文档。
OP_INSERT
Deprecated in MongoDB 5.0. Removed in MongoDB 5.1.
2002Insert new document.插入新文档。
RESERVED2003Formerly used for OP_GET_BY_OID.
OP_QUERY
Deprecated in MongoDB 5.0. Removed in MongoDB 5.1.
2004Query a collection.查询集合。
OP_GET_MORE
Deprecated in MongoDB 5.0. Removed in MongoDB 5.1.
2005Get more data from a query. See Cursors.从查询中获取更多数据。参见Cursors。
OP_DELETE
Deprecated in MongoDB 5.0. Removed in MongoDB 5.1.
2006Delete documents.删除文档。
OP_KILL_CURSORS
Deprecated in MongoDB 5.0. Removed in MongoDB 5.1.
2007Notify database that the client has finished with the cursor.通知数据库客户端已使用完游标。

OP_COMPRESSED

Any opcode can be compressed and wrapped in an OP_COMPRESSED header. The OP_COMPRESSED message contains the original compressed opcode message alongside the metadata necessary to process and decompress it.

The format of the OP_COMPRESSED message is:

struct {
MsgHeader header; // standard message header
int32 originalOpcode; // value of wrapped opcode
int32 uncompressedSize; // size of deflated compressedMessage, excluding MsgHeader
uint8 compressorId; // ID of compressor that compressed message
char *compressedMessage; // opcode itself, excluding MsgHeader
}
Field字段Description描述
MsgHeaderMessage header, as described in Standard Message Header.
originalOpcodeContains the value of the wrapped opcode.包含包装的操作码的值。
uncompressedSizeThe size of the deflated compressedMessage, which excludes the MsgHeader.
compressorIdThe ID of the compressor that compressed the message. A list of compressorId values is provided below.
compressedMessageThe opcode itself, excluding the MsgHeader.

Each compressor is assigned a predefined compressor ID as follows:每个压缩机都分配了一个预定义的压缩机ID,如下所示:

compressorIdHandshake ValueDescription描述
0noopThe content of the message is uncompressed. This is used for testing.消息的内容是未压缩的。这是用于测试的。
1snappyThe content of the message is compressed using snappy.消息的内容使用snappy压缩。
2zlibThe content of the message is compressed using zlib.消息的内容使用zlib压缩。
3zstdThe content of the message is compressed using zstd.消息的内容使用zstd压缩。
4-255reservedReserved for future use.保留供将来使用。

OP_MSG

OP_MSG is an extensible message format used to encode both client requests and server replies on the wire.是一种可扩展的消息格式,用于在网络上对客户端请求和服务器回复进行编码。

OP_MSG has the following format:具有以下格式:

OP_MSG {
MsgHeader header; // standard message header
uint32 flagBits; // message flags
Sections[] sections; // data sections
optional<uint32> checksum; // optional CRC-32C checksum
}
Field字段Description描述
headerStandard message header, as described in Standard Message Header.
flagBitsAn integer bitmask containing message flags, as described in Flag Bits.
sectionsMessage body sections, as described in Sections.
checksumAn optional CRC-32C checksum, as described in Checksum.

Flag Bits标志位

The flagBits integer is a bitmask encoding flags that modify the format and behavior of OP_MSG.

The first 16 bits (0-15) are required and parsers MUST error if an unknown bit is set.

The last 16 bits (16-31) are optional, and parsers MUST ignore any unknown set bits. Proxies and other message forwarders MUST clear any unknown optional bits before forwarding messages.

BitName名称RequestResponseDescription描述
0checksumPresentThe message ends with 4 bytes containing a CRC-32C [2] checksum. See Checksum for details.
1moreToComeAnother message will follow this one without further action from the receiver. The receiver MUST NOT send another message until receiving one with moreToCome set to 0 as sends may block, causing deadlock. Requests with the moreToCome bit set will not receive a reply. Replies will only have this set in response to requests with the exhaustAllowed bit set.
16exhaustAllowed

The client is prepared for multiple replies to this request using the moreToCome bit. The server will never produce replies with the moreToCome bit set unless the request has this bit set.

This ensures that multiple replies are only sent when the network layer of the requester is prepared for them.这确保了只有当请求者的网络层为多个回复做好准备时,才会发送多个回复。

Sections章节

An OP_MSG message contains one or more sections. Each section starts with a kind byte indicating its type. Everything after the kind byte constitutes the section's payload.OP_MSG消息包含一个或多个部分。每个部分都以一个表示其类型的类型字节开头。类型字节之后的所有内容都构成了该部分的有效载荷。

The available kinds of sections follow.可用的章节类型如下。

Kind 0: Body

A body section is encoded as a single BSON object. The size in the BSON object also serves as the size of the section. This section kind is the standard command request and reply body.

All top-level fields MUST have a unique name.

Kind 1: Document Sequence

Type类型Description描述
int32Size of the section in bytes.节的大小(字节)。
C String

Document sequence identifier. In all current commands this field is the (possibly nested) field that it is replacing from the body section.文档序列标识符。在所有当前命令中,此字段是它从主体部分替换的(可能是嵌套的)字段。

This field MUST NOT also exist in the body section.此字段不得也存在于正文部分。

Zero or more BSON objects零个或多个BSON对象
  • Objects are sequenced back to back with no separators.对象是背对背排序的,没有分隔符。
  • Each object is limited to the maxBSONObjectSize of the server. The combination of all objects is not limited to maxBSONObjSize.
  • The document sequence ends once size bytes have been consumed.
  • Parsers MAY choose to merge these objects into the body as an array at the path specified by the sequence identifier when converting to language-level objects.

Kind 2

This section is used for internal purposes.本节用于内部目的。

Checksum

Each message MAY end with a CRC-32C [2] checksum that covers all bytes in the message except for the checksum itself.

If you do not use TLS/SSL connections, mongod instances and mongos instances exchange messages with checksums.

If you use TLS/SSL connections, mongod instances and mongos instances skip the checksum.

Drivers and older binaries will ignore the checksum if presented with messages with checksum.如果显示带有校验和的消息,驱动程序和较旧的二进制文件将忽略校验和。

The presence of a checksum is indicated by the checksumPresent flag bit.校验和的存在由checksumPresent标志位指示。

Legacy Opcodes传统操作码

Starting in MongoDB 5.1, these opcodes are removed in favor of OP_MSG:从MongoDB 5.1开始,这些操作码被删除,取而代之的是OP_MSG

  • OP_DELETE
  • OP_GET_MORE
  • OP_INSERT
  • OP_KILL_CURSORS
  • OP_QUERY [1]
  • OP_REPLY
  • OP_UPDATE

If you are running an older version of MongoDB and need detailed information on the previous opcodes, see Legacy Opcodes.如果您运行的是旧版本的MongoDB,并且需要有关以前操作码的详细信息,请参阅传统操作码

Footnotes

[1] MongoDB 5.1 removes support for both OP_QUERY find operations and OP_QUERY commands. As an exception, OP_QUERY is still supported for running the hello and isMaster commands as part of the connection handshake.
[2](1, 2) 32-bit CRC computed with the Castagnoli polynomial as described by https://tools.ietf.org/html/rfc4960#page-140.