简体   繁体   English

如何在mongodb中生成唯一对象id

[英]How to generate unique object id in mongodb

When I use Mongodb with Java, I want to generate Object id at clients. 当我使用Mongodb和Java时,我想在客户端生成Object id。 Before I insert a record, however, I have to query mongodb first to make sure that the id generated by ObjectId() method is unique. 但是,在插入记录之前,我必须首先查询mongodb以确保ObjectId()方法生成的id是唯一的。 Is there any way that I can generate unique object id without accessing mongodb twice? 有没有办法我可以生成唯一的对象ID而无需访问mongodb两次?

You can generate ObjectId on the client without consulting database. 您可以在客户端生成ObjectId而无需咨询数据库。 Such ID will be unique (you'll have to try damn hard to get two identical object ids). 这样的ID将是唯一的(你必须努力尝试获得两个相同的对象ID)。

ObjectId id = new ObjectId();

// or this
ObjectId id = ObjectId.get();

Object IDs are not like sequential ids you use in a RDMS. 对象ID与您在RDMS中使用的顺序ID不同。 If they are properly generated according to the Object ID specification you will not need to worry about them being unique. 如果根据对象ID规范正确生成它们,则无需担心它们是唯一的。

All you have to do is ensure you always create a new Object ID rather than reusing them. 您所要做的就是确保始终创建新的Object ID而不是重用它们。

As of MongoDB Java Driver 3.3.0, there are the following ways to create ObjectIds. 从MongoDB Java Driver 3.3.0开始,有以下方法可以创建ObjectIds。

Using the constructor without parameters: Provides unique ObjectId 使用不带参数的构造函数: 提供唯一的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 使用参数化构造函数: 参数会影响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:

ObjectId consists of 12 bytes, divided as follows: ObjectId由12个字节组成,分为:

               ObjectID layout

0   1   2   3   4   5   6   7   8   9   10  11

|time          |machine    |pid    |inc      |

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM