javascript - JavaScript 中的 MongoDB ObjectId 解析

标签 javascript mongodb

阅读链接: http://docs.mongodb.org/manual/reference/object-id/

该链接表明 ObjectId 将具有时间、机器、进程 ID 和计数器值。

那么,如何在 JavaScript 中解析 ObjectId 并获取这些详细信息?

最佳答案

在节点中,我们可以使用缓冲区从十六进制字符串中获取整数。

.findOne(cond, function(err, doc){
   // create a 12 byte buffer by parsing the id
   var ctr = 0;
   var b = new Buffer(doc._id.str, 'hex');

   // read first 4 bytes as an integer
   var epoch = b.readUInt32BE(0);
   ctr += 4;

   // node doesn't have a utility for 'read 3 bytes' so hack it
   var machine = new Buffer([0, b[ctr], b[ctr+1], b[ctr+2]]).readUInt32BE(0);
   ctr += 3;

   // read the 2 byte process
   var process = b.readUInt16BE(ctr);
   ctr += 2;

   // another 3 byte one
   var counter = new Buffer([0, b[ctr], b[ctr+1], b[ctr+2]]).readUInt32BE(0);
});

对于驱动程序版本 <2.2,将 doc._id.str 更改为 doc._id.toHexString()

可能更简单的技术是只使用 parseInt 和 slice。因为十六进制数字是一个字节的一半,所以我们的偏移量是原来的两倍。

var id = doc._id.str, ctr = 0;
var epoch   = parseInt(id.slice(ctr, (ctr+=8)), 16);
var machine = parseInt(id.slice(ctr, (ctr+=6)), 16);
var process = parseInt(id.slice(ctr, (ctr+=4)), 16);
var counter = parseInt(id.slice(ctr, (ctr+=6)), 16);

关于javascript - JavaScript 中的 MongoDB ObjectId 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27793242/

相关文章:

javascript - 如何淡化div中背景颜色之间的过渡?

javascript - meteor - 在返回之前同步多个异步查询?

javascript - 在新窗口中打开链接或如果已打开则将焦点移至该链接

PHP:序列化对象并将它们粘贴到数据库中以备后用是不是糟糕的设计?

mongodb - 碎片 : How to write items of different spiders to different MongoDB collections?

regex - 当按 id 查找的功能已实现时,使用查询来搜索任务名称

javascript - 在 CSS 网格布局中使用 em 或百分比

javascript - 如何直接链接到输入字段?

javascript - 路由器在 Express.js 中返回 404

mongodb - 带有副本集 : how to force on secondary? 的 Mongodump