簡體   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