10

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.

Community
  • 1
  • 1
kailniris
  • 8,856
  • 2
  • 17
  • 24

1 Answers1

12

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);                    
    }       
});
chridam
  • 100,957
  • 23
  • 236
  • 235
  • tested with "507f1f77bcf86cd799439011" here are the results: timestamp: 1350508407, machineId: 12384364, processID: 55193, counter: 4427793 These are all good but timestamp 1350508407 does not look ok. new Date(1350508407) = Fri Jan 16 1970 16:08:28 GMT+0100 (Romance Standard Time) – kailniris Aug 19 '16 at 06:28
  • 2
    Timestamp is not in milliseconds, you need to multiply by 1000 first to get the actual date i.e. `new Date(1350508407*1000) = Wed Oct 17 2012 22:13:27 GMT+0100 (GMT Daylight Time)` – chridam Aug 19 '16 at 06:31
  • on what basis the documents are sorted? I see all information identical for data inserted in bulk. – Akshay Naik Dec 04 '19 at 13:46
  • 1
    I'm using this for the counter and I'm seeing duplicate counters for different ID's. Is it supposed to be unique? – Stephen Romero Jul 28 '20 at 19:50