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");
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.