并发性 - 以线程安全的方式获取通过 Java 插入的对象的 MongoDB 生成 ID
获取通过 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尽早生成 ObjectId,在插入中使用它,并且不需要数据库将其返回给您。
ObjectId 不使用共享序列号来保持唯一,因此无论您在插入之前生成序列号还是在插入之后检索它都没有关系。
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.
Mongo 生成的本机 ObjectId 是全局唯一的,可以在多线程应用程序中安全地使用。
生成的ObjectId可以从_id键下的DbObject中获取。
如果插入的文档违反了唯一索引约束 - java 驱动程序可能会抛出异常,具体取决于 WriteConcern 的值:
如果它的值较高,则将抛出 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:
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
我使用 _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.