Read the link: http://docs.mongodb.org/manual/reference/object-id/
The link says that the ObjectId will have Time, Machine, Process Id & Counter values.
Then, how to parse a ObjectId in JavaScript and get those details?
Read the link: http://docs.mongodb.org/manual/reference/object-id/
The link says that the ObjectId will have Time, Machine, Process Id & Counter values.
Then, how to parse a ObjectId in JavaScript and get those details?
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().
The potentially simpler technique is to just use parseInt and 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);