Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate unique object id in mongodb

Tags:

java

mongodb

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?

like image 222
NOrder Avatar asked Jan 04 '12 07:01

NOrder


People also ask

How does MongoDB generate unique IDs?

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.

What is an object ID in MongoDB?

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.

Is MongoDB object ID UUID?

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.

How do I set unique fields in MongoDB?

To create a unique index, use the db. collection. createIndex() method with the unique option set to true .


2 Answers

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(); 
like image 155
Sergio Tulentsev Avatar answered Sep 18 '22 13:09

Sergio Tulentsev


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.

like image 44
Zachary Anker Avatar answered Sep 19 '22 13:09

Zachary Anker