MongoDB handling failure of insert in Java

2019-07-07 05:21发布

问题:

I would like to handle failure of insert to collection (using Java) in order to be sure that my insert was successful. In case that insert fails, I want to perform some fall-back action.

Assuming following code in Java and latest mongo driver (version 2.11.3):

BasicDBObject doc = new BasicDBObject("name", "MongoDB");
WriteResult result = coll.insert(WriteConcern.SAFE, doc);

I am confused by the fact that the insert returns WriteResult and it could throw MongoException. What am I supposed to do in order to safely detect any possible failure of insert? Please, provide code example. And if you can clarify when insert throws exception and when it just returns some error write result. I tried to search in java driver API docs at http://api.mongodb.org/java/2.11.3/ for it; howerever, this infromation is missing there.

WriteResult result;
try {
    result = coll.insert(WriteConcern.SAFE, doc);
}
catch(MongoException ex){
    logger.warn("Insert failed.", ex);
    throw ex;
}

//Shall I check result here for additional errors?  

If I should check, what type of error I am able to detect by checking insert result?

回答1:

You need to take a look at "WriteConcern", it has the all behaviors you need.

You can use it per one write like this:

coll.insert(dbObj, WriteConcern.SAFE);

If you use WriteConcern.SAFE your operation will wait for an acknowledgement from the primary server, so if no exception is raised then you're ok.

Or you can set default behaviour for all write operations when you are creating MongoClient:

MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
builder.writeConcern(WriteConcern.JOURNAL_SAFE);
MongoClient mongoClient = new MongoClient(
    new ServerAddress("localhost"), builder.build());

[Based on Colin Morelli's comment] If you don't use a WriteConcern that raises exceptions, you can use the WriteResult.getLastError() to determine if it was successful or not. Similarly, if you use WriteConcern.SAFE, and the write succeeds, WriteResult will have useful information on it such as the number of records that were written.

Here you can read about WriteConcern in general.