Reputation: 1617
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
Upvotes: 1
Views: 724
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