我们现有的代码包含很少基于集合操作的writeResult的操作,如:
WriteResult writeResult = dbCollection.insert(new BasicDBObject(someDoc));
if(writeResult.wasAcknowledged()) {
response.setSuccess(true);
}
使用升级的mongo更改操作会产生如下结果:
WriteResult writeResult = dbCollection.insertOne(new BasicDBObject(someDoc)); // this won't work
if (writeResult.wasAcknowledged()) {
response.setSuccess(true);
}
问题是对集合的操作是void
,如果我查看文档 -
WriteResult.java
/**
* Returns true if the write was acknowledged.
*
* @return true if the write was acknowledged
* @see com.mongodb.WriteConcern#UNACKNOWLEDGED
* @since 3.0
*/
public boolean wasAcknowledged() {
return acknowledged;
}
WriteConcern.java
/**
* Write operations that use this write concern will return as soon as the message is written to the socket. Exceptions are raised for
* network issues, but not server errors.
*
* @since 2.10.0
* @mongodb.driver.manual core/write-concern/#unacknowledged Unacknowledged
*/
public static final WriteConcern UNACKNOWLEDGED = new WriteConcern(0);
我尝试修改代码以获得如下结果:
collection.withWriteConcern(WriteConcern.UNACKNOWLEDGED).insertOne(document);
但是,我现在如何使用当前代码实现前一逻辑的条件部分?
答案 0 :(得分:2)
根据MongoCollection
/**
* Inserts the provided document. If the document is missing an identifier, the driver should generate one.
*
* @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);
如果由于无法满足写入问题而导致写入失败,则插入操作应抛出com.mongodb.MongoWriteConcernException
所以你的代码可以转换为:
try {
dbCollection
.withWriteConcern(WriteConcern.ACKNOWLEDGED)
.insertOne(new BasicDBObject(someDoc));
response.setSuccess(true);
} catch (MongoWriteConcernException x) {
response.setSuccess(false);
}