Abhiram mishra
Abhiram mishra

Reputation: 1617

update/upsert if duplicatekeyexception on insert mongodb java driver

My application mostly does insert operation to mongodb by using mongodb java driver 3.2.2.

I would receive an document which I would have to insert, about 90% of the time, and I have two unique key indexes defined on my collection.Occasionally when I receive a duplicate element , I am relying on the the driver throwing me an exception DuplicateKeyException, on which I know I want to update the document.

My document would look something like below:

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

My Java code looks like below.

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

I have the following questions

  1. Am I on right track ? I am trying to reduce any network round trip,by going with this approach.
  2. The data am receiving in case of duplicate element could be very different from the original one , and am not sure which of the fields could have changed. so am not sure what operation I should choose update/upsert little confused here.

Upvotes: 1

Views: 724

Answers (1)

profesor79
profesor79

Reputation: 9473

you can turn your insert into update with UPSERT flag ref this will reduce exception handling, and insert new document where ID not exists, also save network traffic.

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

Upvotes: 1

Related Questions