当我使用Java与Mongodb时,我想在客户端生成对象ID。然而,在插入记录之前,我必须先查询mongodb,以确保ObjectId()方法生成的ID是唯一的。有没有办法只访问一次mongodb就生成唯一的对象ID?
你可以在客户端生成ObjectId而无需查询数据库。这样的ID将是唯一的(你必须极力尝试才能获得两个相同的对象ID)。
ObjectId id = new ObjectId();
// or this
ObjectId id = ObjectId.get();
对象ID不像您在关系型数据库中使用的顺序ID一样。如果它们根据对象ID规范正确生成,则无需担心其唯一性。
您需要做的就是确保始终创建新的对象ID而不是重复使用它们。
从MongoDB Java Driver 3.3.0开始,有以下几种方法可以创建ObjectId。
使用不带参数的构造函数:提供唯一的ObjectId
1. ObjectId id1 = new ObjectId(); //Generates unique id
1.1. ObjectId id2 = ObjectId.get(); //Calls new ObjectId();
使用参数化构造函数:参数影响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.
了解ObjectId:
ObjectId由12个字节组成,分别如下:
ObjectID layout
0 1 2 3 4 5 6 7 8 9 10 11
|time |machine |pid |inc |