繁体   English   中英

如果在插入 mongodb java 驱动程序时出现重复键异常,则更新/更新插入

[英]update/upsert if duplicatekeyexception on insert mongodb java driver

我的应用程序主要使用 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. 在重复元素的情况下收到的数据可能与原始数据非常不同,并且不确定哪些字段可能已更改。 所以我不确定我应该选择什么操作更新/upsert 在这里有点困惑。

您可以使用 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM