[英]MongoDB ObjectId parsing in JavaScript
Read the link: http://docs.mongodb.org/manual/reference/object-id/ 阅读链接: http : //docs.mongodb.org/manual/reference/object-id/
The link says that the ObjectId will have Time, Machine, Process Id & Counter values. 该链接表示ObjectId将具有时间,机器,进程ID和计数器值。
Then, how to parse a ObjectId in JavaScript and get those details? 然后,如何在JavaScript中解析ObjectId并获取这些详细信息?
In node we can make use of buffers to grab integers from a hex string. 在节点中,我们可以利用缓冲区从十六进制字符串中获取整数。
.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);
});
For driver version <2.2 change doc._id.str
to doc._id.toHexString()
. 对于驱动程序版本<2.2,将
doc._id.str
更改为doc._id.toHexString()
。
The potentially simpler technique is to just use parseInt and slice. 可能更简单的技术是仅使用parseInt和slice。 Because hex digits are half of a byte our offsets are twice as high.
因为十六进制数字是一个字节的一半,所以我们的偏移量是原来的两倍。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.