首页 > 解决方案 > MongoDB,WriteConcern:需要澄清一下

问题描述

我需要一些帮助来澄清 WriteConcern 的概念我正在使用 MongoDb 4.0.2(带有副本集)和 java-mongo-driver 3.8.1

我已经在 mongo 配置中添加了最后一个默认写入问题

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

在代码方面,我什么时候可以使用来自数据库的 ack 响应?我发现,当您使用删除或更新时,该库会返回一个 Result 对象(作为 DeleteResult),其中包含一个函数wasAcknowledged(),用于获取集合中多数副本的删除/更新结果。

但我无法为所有插入功能找到类似的结果。有人可以向我解释如何使用 WriteConcern 以避免数据丢失?

我的目标是在副本集上的插入/写入/更新出错时捕获异常

希望问题很清楚,我正在等待您的回答。谢谢

只是要知道,在 db 上设置此首选项是否足够,或者我还必须在我的代码上设置 write-concern 首选项?

标签: javamongodb

解决方案


你可以抓到MongoWriteConcernException。以下是 的源代码和注释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);

推荐阅读