Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb get the 3-byte counter from an ObjectId

How/Can I get the

3-byte counter, starting with a random value

part from a mongodb ObjectId?

I have an ObjectId like this: ObjectId("507f1f77bcf86cd799439011")

According to mongodb documentation:

Description

ObjectId() Returns a new ObjectId value. The 12-byte ObjectId value consists of:

a 4-byte value representing the seconds since the Unix epoch,

a 3-byte machine identifier,

a 2-byte process id,

and a 3-byte counter, starting with a random value.

I want to get the "and a 3-byte counter, starting with a random value." part from the ObjectId above if its possible.

like image 300
kailniris Avatar asked Aug 18 '16 12:08

kailniris


People also ask

Is MongoDB ObjectId ordered?

No. Since ObjectIDs are typically generated on the client, the deployment topology does not factor into the ordering of ObjectIDs. Even if the ObjectIDs are generated on the server, multiple ObjectIDs generated in the same second will not have a predictable ordering.

What is the size of an ObjectId in MongoDB?

ObjectId values are 12 bytes in length, consisting of: A 4-byte timestamp, representing the ObjectId's creation, measured in seconds since the Unix epoch. A 5-byte random value generated once per process. This random value is unique to the machine and process.

What is ObjectId in MongoDB?

An ObjectId is a 12-byte BSON type having the following structure − The first 4 bytes representing the seconds since the unix epoch. The next 3 bytes are the machine identifier. The next 2 bytes consists of process id. The last 3 bytes are a random counter value.

How many bytes is ObjectId?

An ObjectId is a 12-byte unique identifier consisting of: a 4-byte value representing the seconds since the Unix epoch, a 5-byte random value, a 3-byte counter, starting with a random value.


1 Answers

You could try the following hack where you can get the equivalent string representation of the ObjectId using toString() or toHexString(), use parseInt and slice to get the parts. Because hex digits are half of a byte the offsets are twice as much:

db.collection("collectionName").findOne({}, function(err, result) {     
    if (result) {
        var id          = result._id.toString(), ctr = 0;
        var timestamp   = parseInt(id.slice(ctr, (ctr+=8)), 16);
        var machineID   = parseInt(id.slice(ctr, (ctr+=6)), 16);
        var processID   = parseInt(id.slice(ctr, (ctr+=4)), 16);
        var counter     = parseInt(id.slice(ctr, (ctr+=6)), 16);
        console.log(id);
        console.log(timestamp);
        console.log(machineID);
        console.log(processID);
        console.log(counter);                    
    }       
});
like image 51
chridam Avatar answered Sep 20 '22 17:09

chridam