carmelolg
carmelolg

Reputation: 503

MongoDB, WriteConcern: need some clarification

I need some help to clarify the concept of WriteConcern I'm using MongoDb 4.0.2 (with a replicaset) and java-mongo-driver 3.8.1

I already added on mongo configuration the last default write concern with

{
    "w": "majority",
    "wtimeout": 5000
}

In code-side, when can I use the ack response from the database? I found that the library, when you use delete or update, return an object of Result (as DeleteResult) that contain a function wasAcknowledged() for take the result of delete/update on the majority replica in the set.

But I'm not able to find a similar Result for all insert function. Someone could explain me how to use WriteConcern in order to avoid data loss?

My goal is catch an Exception when insert/write/update on replica-set going in error

Hope the question is clear, I'm waiting for your answer. Thanks

Just to know, is enough set this preferences on db, or I have to set the write-concern preferences also on my code?

Upvotes: 0

Views: 700

Answers (1)

simagix
simagix

Reputation: 1912

You can catch MongoWriteConcernException. Below are the source codes and comments for insertOne.

/**
 * Inserts the provided document. If the document is missing an identifier, the driver should generate one.
 *
 * <p>Note: Supports retryable writes on MongoDB server versions 3.6 or higher when the retryWrites setting is enabled.</p>
 * @param document the document to insert
 * @throws com.mongodb.MongoWriteException        if the write failed due some other failure specific to the insert command
 * @throws com.mongodb.MongoWriteConcernException if the write failed due being unable to fulfil the write concern
 * @throws com.mongodb.MongoException             if the write failed due some other failure
 */
void insertOne(TDocument document);

Upvotes: 2

Related Questions