Question

I am a little confused about WriteConcern, WriteResult, and getLastError when using the java mongo driver.

I understand what the different WriteConcerns mean as in WriteConcern.SAFE causes the write operation to block until the driver receives confirmation from the mongodb server. I am confused as too what happens when there is a problem writing.

For example

DBCollection collectionHandle = ...
DBObject criteria = ...
WriteResult result = collectionHandle.remove(criteria, WriteConcern.SAFE)

If the write operation fails, how do I detect the failure? Does the driver's 'remove'call throw an exception? Does one need to check WriteResult? If checking the WriteResult would one call getError or getLastError?

Thanks,

Nathan

Was it helpful?

Solution

If the write operation fails, how do I detect the failure? Does the driver's 'remove'call throw an exception?

Yes, you are right. If you are using WriteConcern.SAFE (and above), the driver internally examines the getLastError and throws an exception if the result document contains err. So in that case you don't have to check WriteResult. This is also true for String based write concern such as "majority".

For "lower" WriteConcern (NORMAL or NONE) the drivers just returns a WriteResult and doesn't throw an exception. You will have to manually inspect it's error property. If everything went well it's null, otherwise an error has occurred.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top