3

Add some records to collection with java driver, it will generate object id for each records automatically. In my database, it generate below Object Id by MongoDB:

ObjectId("58b38cd57decdd8070b2df8f")

Then I make a test for current object id:

import org.bson.types.ObjectId;
public class Test {
    public static void main(String[] args)
    { 
        // TODO Auto-generated method stub String 
        idStr = "58b38cd57decdd8070b2df8f"; 
        ObjectId id = new ObjectId(idStr);
        System.out.println(id.getProcessIdentifier()); 
    }
}

java no error with below print result: -32656

The process Identifier is a negative number in object id structure. I'm not sure it's a java driver bug or core server bug.

In my project, I need to post object id to JSP file, and generate object id by object structure posted. Because invalid process identifier, the object id generated by JS function will contains en dash. It's an invalid object id.

object structure posted to JSP file:

counter:11722639
date:1488162005000
machineIdentifier:8252637
processIdentifier:-32656
time:1488162005000
timeSecond:1488162005
timestamp:1488162005

The new object id generated by object structure:

58b38cd57decdd-7f90b2df8f

The JS function generated object id by object structure:

function parseObjectId(objectId){
var timestamp = objectId.timestamp;
var machineIdentifier = objectId.machineIdentifier;
var processIdentifier = objectId.processIdentifier;
var counter = objectId.counter;
return toFixedLengthHex(timestamp,8) + toFixedLengthHex(machineIdentifier,6) + toFixedLengthHex(processIdentifier,4) + toFixedLengthHex(counter,6);

}

mongodb version:3.4.1 BSON version:3.2.1 Mongo-java-driver:3.2.2

Kimi Liu
  • 33
  • 4

1 Answers1

1

In order to fix this issue is to add 65536 to the process Identifier when converting it to a hex, this is because the negative value you get from the hex is 2's compliment of what you actually need. I would only add that value if the number is negative.

var processIdentifier = objectId.processIdentifier;
if(processIdentifier < 0) processIdentifier += 65536;