Concurrency - Getting the MongoDB generated ID of an object inserted via Java in a thread safe way

喜你入骨 提交于 2019-12-07 01:13:38

问题


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!


回答1:


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;
}



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/7860773/concurrency-getting-the-mongodb-generated-id-of-an-object-inserted-via-java-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!