How to generate unique object id in mongodb

前端 未结 3 696
醉话见心
醉话见心 2020-12-05 23:29

When I use Mongodb with Java, I want to generate Object id at clients. Before I insert a record, however, I have to query mongodb first to make sure that the id generated by

相关标签:
3条回答
  • 2020-12-05 23:39

    As of MongoDB Java Driver 3.3.0, there are the following ways to create ObjectIds.

    Using the constructor without parameters: Provides unique ObjectId

    1. ObjectId id1 = new ObjectId(); //Generates unique id 
    
        1.1. ObjectId id2 = ObjectId.get(); //Calls new ObjectId();
    

    Using the parameterized constructors: Parameters influence the uniqueness of the ObjectId

    2. public ObjectId(byte[] bytes) // Receives a byte array of size 12.
    
    3. public ObjectId(String hexString) //Receives a String that is a hexadecimal representation of 12 bytes.
    
    4. public ObjectId(Date date) // Receives a Date object
    
    5. public ObjectId(Date date, int counter) //Receives date and a counter
    
    6. public ObjectId(Date date,
                int machineIdentifier,
                short processIdentifier,
                int counter) //Receives Date, MachineId, PID and counter.
    
    7. public ObjectId(int timestamp,
                int machineIdentifier,
                short processIdentifier,
                int counter) //Receives Epoch time in sec, MachineId, PID and counter.
    

    Understanding ObjectId:

    ObjectId consists of 12 bytes, divided as follows:

                   ObjectID layout
    
    0   1   2   3   4   5   6   7   8   9   10  11
    
    |time          |machine    |pid    |inc      |
    
    0 讨论(0)
  • 2020-12-05 23:49

    You can generate ObjectId on the client without consulting database. Such ID will be unique (you'll have to try damn hard to get two identical object ids).

    ObjectId id = new ObjectId();
    
    // or this
    ObjectId id = ObjectId.get();
    
    0 讨论(0)
  • 2020-12-05 23:54

    Object IDs are not like sequential ids you use in a RDMS. If they are properly generated according to the Object ID specification you will not need to worry about them being unique.

    All you have to do is ensure you always create a new Object ID rather than reusing them.

    0 讨论(0)
提交回复
热议问题