![](/img/trans.png)
[英]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.