Concurrency - Getting the generated MongoDB identifier of an object inserted through Java in streaming mode

What is the best way to get the generated Mongo ID of a document inserted through Java.

The Java process that inserts documents is multi-threaded, which means that we need some atomic way to insert and return the object identifier.

In addition, if we set a unique index, in case the object is a duplicate, will the ID be returned?

Thanks!

+7
source share
3 answers

Generate an ObjectId earlier, use it in the insert, and there is no need for the database to return it to you. ObjectId does not use a common sequence number to be unique, so it does not matter if you generate it before inserting or retrieving after it.

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

The native ObjectId that Mongo generates is unique worldwide and can be safely used from a multi-threaded application.

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

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

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

If the value is greater, a NORMAL exception will be thrown.

WriteConcern can be specified for each individual insertion (or update) method or globally using DBCollection.setWriteConcern

+1
source

I retrieve the document using _id, but when I get the data in my java class, for example, a mobile, _id attribute that is of type ObjectID me, I change it by setting the value of the document to mongodb.

+1
source

All Articles