[英]Check if there is an error in update/insert | MongoDB Java driver
[英]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,
}
我有以下问题
您可以使用 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.