Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB ObjectId parsing in JavaScript

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?

like image 730
sarathmojo Avatar asked Sep 20 '26 13:09

sarathmojo


1 Answers

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);
like image 134
Brigand Avatar answered Sep 23 '26 03:09

Brigand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!