cledoux
cledoux

Reputation: 4947

Possible to set mongodb writeconcern to only ignore Duplicate Key errors?

On an insert into mongodb, can I set the writeconcern to something that will only ignore Duplicate Key errors? I want to completely ignore these errors, but still catch if something else went wrong. I'd especially like to know if I've lost my connection to the database or if mongod itself has crashed. (I'm on a research network, so these two things aren't always the most reliable.)

The writeconcern I see that seems to come close is UNACKNOWLEDGED, but I don't quiet understand what exactly it'll catch and what will be ignored.

My application is written in Java with mongo driver version 2.10.1 and using mongo version 2.4.6

I'm avoiding using the default writeconcern and simply catching the exception because I don't want the exception overhead. I expect the number of Duplicate Keys to be high. Is this a silly concern?

Upvotes: 0

Views: 1905

Answers (1)

Philipp
Philipp

Reputation: 69663

The official documentation about WriteConcern shows what options the WriteConcern setting has.

The WriteConcern.UNACKNOWLEDGED ({w:0,j:0,fsync:0}) will report network errors, so you already have that covered. When the database crashes, the connection to it will be interrupted immediately (when the operating system is still running) or time out in a few seconds (when the whole OS or even the physical server crashes), so you should also notice that rather quickly.

The next best WriteConcern ({w:1,j:0,fsync:0}, or WriteConcern.SAFE) waits for acknowledgment by the primary of the replica-set, so it will report primary key unique index errors.

When there would be a setting which would make the server respond after it received the data but before it interpreted it, it wouldn't be much faster. Validating the BSON syntax is usually cheap, and checking for collisions in any unique indexes isn't that much more expensive. At least compared to the network roundtrip time.

When you worry about performance of catching the exception in Java: Exception handling in Java isn't expensive either.

Upvotes: 3

Related Questions