RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
理解MongoDB默认的ObjectID-创新互联

BSON ObjectID Specification

A BSON ObjectID is a 12-byte value consisting of a 4-byte timestamp (seconds since epoch), a 3-byte machine id, a 2-byte process id, and a 3-byte counter. Note that the timestamp and counter fields must be stored big endian unlike the rest of BSON. This is because they are compared byte-by-byte and we want to ensure a mostly increasing order. The format:

成都创新互联从2013年开始,是专业互联网技术服务公司,拥有项目做网站、成都做网站网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元洛隆做网站,已为上家服务,为洛隆各地企业和个人服务,联系电话:18980820575

0 1 2 3 4 5 6 7 8 9 10 11
time machine pid inc

  • TimeStamp. This is a unix style timestamp. It is a signed int representing the number of seconds before or after January 1st 1970 (UTC).
  • Machine. This is the first three bytes of the (md5) hash of the machine host name, or of the mac/network address, or the virtual machine id.
  • Pid. This is 2 bytes of the process id (or thread id) of the process generating the object id.
  • Increment. This is an ever incrementing value, or a random number if a counter can't be used in the language/runtime.

BSON ObjectIds can be any 12 byte binary string that is unique; however, the server itself and almost all drivers use the format above.

分段查看ObjectId的指令及结果如下:

  1. > db.test.findOne()._id.toString()  
  2. "50c6b336ba95d7738d1042e3"

ObjectId占用12字节的存储空间,由“时间戳” 、“机器名”、“PID号”和“计数器”组成。使用机器名的好处是在分布式环境中能够避免单点计数的性能瓶颈。使用PID号的好处是支持同一机器内运行多个mongod实例。最终采用时间戳和计数器的组合来保证唯一性。

时间戳

确保ObjectId唯一性依赖的是时间的顺序,不依赖时间的取值,因此集群节点的时间不必完全同步。既然ObjectId已经有了时间戳,那么在文档中就可以省掉一个时间戳了。在使用ObjectID提取时间时,应注意到MongoDB允许各节点时间不一致这一细节。

下面是查看时间戳的两种写法:

  1. > db.test1.findOne()._id.getTimestamp()
  2. "2012-12-12T03:52:45Z"

机器名

机器名通过Md5加密后取前三个字节,应该还是有重复概率的,配置生产集群时检查一下总不会错。另外,我也注意到重启MongoDB后MD5加密结果会发生变化,在利用ObjectID提取机器名信息时需格外注意。

PID号

注意到每次重启mongod进程后PID号通常会发生变化就可以了。

计数器

计数器占3个字节,表示的取值范围就是256*256*256-1=16777215。不妨认为MongDB性能的极限是单台设备一秒钟插入一千万条记录。以目前的水平看,单台设备一秒钟插入一万条就很不错了,因此ObjectID计数器的设计是够用的。

循环插入了一些记录,下面的查询中b是循环计数器,可以看出我机器上的ObjectId计数器是按顺序增加的:

  1. > parseInt(db.test.findOne({b:1000})._id.toString().substring(28,34),16)  

以下代码源自:http://www.cnblogs.com/xjk15082/archive/2011/09/18/2180792.html

  1. 构建objectId  
  2. publicclass
  3. int
  4. int
  5. int
  6. public
  7. int
  8. true
  1. 机器码和进程码的生成  
  2. privatestaticint
  3. static
  4. try
  5. int
  6. new
  7. while
  8. "machine piece post: "
  9. int
  10. intnew
  11. try
  12. catch
  13. class
  14. int
  15. new
  16. "process piece: "
  17. "machine : "
  18. catch
  19. thrownew

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


新闻名称:理解MongoDB默认的ObjectID-创新互联
网址分享:http://cqwzjz.cn/article/hdjgo.html