并发性 - 以线程安全的方式获取通过 Java 插入的对象的 MongoDB 生成 ID

发布于 2024-12-11 12:09:35 字数 150 浏览 5 评论 0原文

获取通过 Java 插入的文档的 Mongo 生成 ID 的最佳方法是什么?

插入文档的 Java 进程是多线程的,这意味着我们需要某种原子方式来插入和返回对象的 ID。

另外,如果我们设置唯一索引,如果对象重复,是否会返回ID?

谢谢!

What is the best method to get the Mongo generated ID of a document inserted via Java.

The Java process inserting the documents is multi-thread, meaning that we need some atomic way to insert and return the ID of the object.

Also, if we setup a unique index, in the event that the object is a duplicate, will an ID be returned?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

软的没边 2024-12-18 12:09:35

尽早生成 ObjectId,在插入中使用它,并且不需要数据库将其返回给您。
ObjectId 不使用共享序列号来保持唯一,因此无论您在插入之前生成序列号还是在插入之后检索它都没有关系。

public ObjectId createThing() {
    ObjectId result = new ObjectId();
    BasicDBObject thingToInsert = new BasicDbObject();
    thingToInsert.put('_id', result);
    //set other fields here
    collection.insert(thingToInsert);
    return result;
}

Generate the ObjectId early, use it in the insert, and there will no need to have the database return it to you.
ObjectId doesn't use a shared sequence number to be unique, so it doesn't matter if you generate one before inserting or retrieve it after.

public ObjectId createThing() {
    ObjectId result = new ObjectId();
    BasicDBObject thingToInsert = new BasicDbObject();
    thingToInsert.put('_id', result);
    //set other fields here
    collection.insert(thingToInsert);
    return result;
}
夜唯美灬不弃 2024-12-18 12:09:35

Mongo 生成的本机 ObjectId 是全局唯一的,可以在多线程应用程序中安全地使用。

生成的ObjectId可以从_id键下的DbObject中获取。

如果插入的文档违反了唯一索引约束 - java 驱动程序可能会抛出异常,具体取决于 WriteConcern 的值:

 http://api.mongodb.org/java/current/com/mongodb/WriteConcern.html

如果它的值较高,则将抛出 NORMAL - 异常。

可以为每个单独的插入(或更新)方法指定 WriteConcern,或者使用 DBCollection.setWriteConcern 全局指定

native ObjectId's which are generated by Mongo are globally unique and can be safely used from the multi-threaded application.

generated ObjectId can be obtained from the DbObject under _id key.

If inserted document violates a unique index constraint - java driver may throw an exception, depending on a value of WriteConcern:

 http://api.mongodb.org/java/current/com/mongodb/WriteConcern.html

If it's value is higher then NORMAL- exception will be thrown.

WriteConcern can be specified for every individual insert (or update) method, or globally by using DBCollection.setWriteConcern

国产ˉ祖宗 2024-12-18 12:09:35

我使用 _id 检索文档,但是当我将数据获取到我的 java 类(例如 mobile)时,ObjectID 类型的 _id 属性我更改它,在 mongodb 中设置文档的值。

I retrieve the document with _id but when I get the data into my java class eg mobile, _id attribute which is of type ObjectID me I change it set the value of the document in mongodb.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文