2016-03-20 217 views
1

私のアプリケーションは、主にmongodb javaドライバ3.2.2を使用してmongodbに操作を挿入します。update/upsertを挿入するとduplicatekeyexceptionが発生する

時間の約90%を挿入しなければならない文書を受け取り、私のコレクションに2つの一意のキーインデックスが定義されています。重複要素を受け取ったときに、ドライバに依存していますDuplicateKeyExceptionを例外として投げてしまいました。私はその文書を更新したいと思っています。私のJavaコードは以下のようになります

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

マイドキュメントは、以下のようになります。

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

I正しい軌道上で次の質問

  1. アムIを持っていますか?私は、このアプローチで行くことで、ネットワークのラウンドトリップを減らそうとしています。
  2. 重複した要素の場合に受信しているデータは、元のデータと大きく異なる場合があり、どのフィールドが変更された可能性があるのか​​不明です。だから、私が選択しなければならない操作は、ここで少し混乱したアップデート/アップサートを選ぶべきか分からない。

答えて

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 
関連する問題