阅读链接: 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/