【问题标题】:update/upsert if duplicatekeyexception on insert mongodb java driver如果在插入 mongodb java 驱动程序上出现重复键异常,则更新/更新
【发布时间】:2016-03-21 05:35:35
【问题描述】:

我的应用程序主要使用 mongodb java driver 3.2.2 对 mongodb 进行插入操作。

大约 90% 的时间我会收到一个我必须插入的文档,并且我的集合中定义了两个唯一的键索引。有时当我收到一个重复的元素时,我依赖于驱动程序抛出我是一个异常 DuplicateKeyException,我知道我想更新文档。

我的文档如下所示:

{_id:{Object....},
name:"something", //unique key
rollNo:1232,   //unique key combined with name
otherfields
}

我的 Java 代码如下所示。

try{
dbCollections.insert(dbObject);
}catch(DuplicateKeyException e){
// since it is duplicate , lets just update it, 
}

我有以下问题

  1. 我在正确的轨道上吗?我正在尝试通过这种方法减少任何网络往返。
  2. 在重复元素的情况下接收的数据可能与原始数据有很大不同,并且不确定哪些字段可能已更改。所以我不确定我应该选择什么操作 update/upsert 这里有点困惑。

【问题讨论】:

    标签: java mongodb


    【解决方案1】:

    您可以使用 UPSERT 标志 ref 将您的插入转换为更新,这将减少异常处理,并在 ID 不存在的地方插入新文档,还可以节省网络流量。

    UpdateResult updateOne(Bson filter,
                           Bson update,
                           UpdateOptions updateOptions)
    Update a single document in the collection according to the specified arguments.
    Parameters:
    filter - a document describing the query filter, which may not be null.
    update - a document describing the update, which may not be null. The update to apply must include only update operators.
    updateOptions - the options to apply to the update operation
    Returns:
    the result of the update one operation
    Throws:
    MongoWriteException - if the write failed due some other failure specific to the update command
    MongoWriteConcernException - if the write failed due being unable to fulfil the write concern
    MongoException - if the write failed due some other failure
    

    【讨论】:

      猜你喜欢
      • 2012-04-21
      • 2015-02-24
      • 2017-08-02
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2013-08-02
      • 2015-07-04
      • 1970-01-01
      相关资源
      最近更新 更多