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 ObjectId() method is unique. Is there any way that I can generate unique object id without accessing mongodb twice?
MongoDB uses ObjectIds as the default value of _id field of each document, which is generated during the creation of any document. Object ID is treated as the primary key within any MongoDB collection. It is a unique identifier for each document or record.
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.
By default, the MongoDB Java driver generates IDs of the type ObjectId. Sometimes, we may want to use another type of data as the unique identifier of an object, such as a UUID. However, the MongoDB Java driver can't generate UUIDs automatically.
To create a unique index, use the db. collection. createIndex() method with the unique option set to true .
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With