Mongo Wire Protocol(写MongoDB驱动必备)

来源:互联网 发布:如何开通企业邮箱域名 编辑:程序博客网 时间:2024/06/11 23:41

目前MongoDB针对各种语言都已经有了相应的驱动,但是写好一个驱动的关键是理解MongoDB提供的协议,下面的内容主要是来自MongoDB的官方的Protocol描述:

 

  • Introduction

The Mongo Wire Protocol is a simple socket-based, request-response style protocol. Clients communicate with the database server through a regular TCP/IP socket.

 

  • 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 :


 

MsgHeader一个关键的field就是opCode,它决定了Message是干什么用的,比如OP_QUERY肯定是客户端向MongoDB服务器发送的查询请求。

 

  • Request Opcodes

 

Client能够使用除OP_REPLY以外的所有Opcode,而OP_REPLY是留给Mongodb用的;

Client发送的Opcode中,只有OP_QUERY和OP_GET_MORE会得到MongoDB的response,对于其他的Opcode一概不给予答复(如果你真的需要看你发送的opcode是否执行成功,可以调用getLastError查看);

  • Client Request Messages

OP_UPDATE 

 

The OP_UPDATE message is used to update a document in a collection. The format of a OP_UPDATE message is:

 

 

 

MsgHeader是每一个Message必须有的;fullCollectionName就是db + collection name;flags就是一个位描述符,每一位代表的意思如下:

 

 

Upsert就是当要更新的document不存在的时候,是否将其插入到collection中去,MultiUpdate则表示当selector找到了多个符合更新条件的document时,是否将它们全部更新; selector决定了选择哪些document去做更新操作,它也是经常用在find中的;update则表示要将找到的document更新成什么模样,也能是一部分field,或者全部field。

 

OP_INSERT

 

The OP_INSERT message is used to insert one or more documents into a collection. The format of the OP_INSERT message is:

 

 

 

需要注意的就是flags每位代表的意思改变了,具体查看:http://www.mongodb.org/display/DOCS/Mongo+Wire+Protocol

 

OP_QUERY

 

The OP_QUERY message is used to query the database for documents in a collection. The format of the OP_QUERY message is :

 

 

 

numberToSkip有skip参数决定了,表示要对查找到的document跳过多少个;numberToReturn则由limit参数决定了,表示要返回多少个document给client;query就是个查询条件;returnFieldSelector则表示返回哪些docuemnt的fields回来,因为我们也有是需要document的部分field的情况,而不是所有的fields。

 

OP_GETMORE

 

The OP_GETMORE message is used to query the database for documents in a collection. The format of the OP_GETMORE message is :

 

 

 

一般mongoDB做查询的时候返回的是Cursor对象,它并不包含实际的数据,而只是数据的一些标识,当我们需要具体的document的时候可以调用Cursor的方法来向mongoDB请求数据,这个时候发送的Opcode就是OP_GETMORE了,所以cursorID就是告诉MongoDB返回从哪个位置开始的数据罢了。

 

OP_DELETE

 

The OP_DELETE message is used to remove one or more messages from a collection. The format of the OP_DELETE message is :

 

 

 

  • Database Response Messages

 

OP_REPLY

 

The OP_REPLY message is sent by the database in response to an CONTRIB:OP_QUERY or CONTRIB:OP_GET_MORE 
message. The format of an OP_REPLY message is:

 

 

 

更多的Opcode请参考:http://www.mongodb.org/display/DOCS/Mongo+Wire+Protocol

原创粉丝点击