2

I'm using spring framework with mongoTemplate. bean initiation:

public
@Bean
MongoTemplate mongoTemplate() throws Exception {
    MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
    mongoTemplate.setWriteResultChecking(WriteResultChecking.EXCEPTION);

    return mongoTemplate;
}

in short this code does not fail on duplicate key

collection= mTemplate.getCollection("col");
try {
        final WriteResult writeResult = collection.insert(edge);

} catch (DuplicateKeyException e) {
        log.warn("@error> edge already exists");

        return null;
}

writeResult._lastErrorResult is not null and has the relevant errors.

the document i'm trying to insert: Also I've tried to catch Exception e without success.

collection.createIndex(new BasicDBObject("a", 1).append(, 1), unique);
DbObject edge = new BasicDBObject("a", "123").append("b", "345");
royB
  • 12,779
  • 15
  • 58
  • 80
  • Please post the document that you tried inserting and a snapshot of the collection with the relevant id in question. – BatScream Dec 26 '14 at 21:22
  • 1
    Try setting the WriteConcern to `SAFE`.http://api.mongodb.org/java/current/com/mongodb/WriteConcern.html. It seems that the driver is not waiting for an acknowledgement from the primary server. – BatScream Dec 26 '14 at 23:56
  • yeah that did the trick. i thought setting WriteresultChecking.EXCEPTION is enough. anyhow `SAFE` will probably going to be deprecated soon so should use `WriteConcern.ACKNOWLEDGED` – royB Dec 27 '14 at 07:28
  • btw @BatScream you are more than welcome to add an answer which i will accept. – royB Dec 27 '14 at 11:37

1 Answers1

3

You need to set the WriteConcern of the MongoDB driver to Acknowledged.

From the docs,

Write operations that use this write concern will wait for acknowledgement from the primary server before returning. Exceptions are raised for network issues, and server errors.

BatScream
  • 19,260
  • 4
  • 52
  • 68