Competition - Obtaining the MongoDB generated the ID of an object inserted via Java in a secure way

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!


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