-
Type: Bug
-
Resolution: Won't Fix
-
Priority: Major - P3
-
None
-
Affects Version/s: 2.13.1
-
Component/s: Error Handling, Write Operations
-
None
When doing an update() operation with upsert=true, sometimes you can get into a situation where it tries to insert a duplicate key into the collection.
When this happens, update() will throw a DuplicateKeyException, as expected.
However, if you attempt the exact same modification using findAndModify() instead of update(), and you trigger the exact same duplicate key condition, you won't get a DuplicateKeyException, as you might expect. You get a CommandFailureException instead.
This can introduce subtle bugs if you have some existing logic that might depend on catching a DuplicateKeyException during atomic update() operations, and you decide you need some extra functionality from findAndModify(), while expecting your existing DuplicateKeyException handler to keep working as before...
See the attached DuplicateKeyBug.java for a self-contained example of this problem. Run it against org.mongodb:mongo-java-driver:2.13.1.
The expected output from this program would be:
Duplicate key detected during update(upsert=true), as expected Duplicate key detected during findAndModify(upsert=true), as expected
Instead, I get this output when I run it:
Duplicate key detected during update(upsert=true), as expected Unexpected exception from findAndModify(upsert=true): com.mongodb.CommandFailureException: { "serverUsed" : "127.0.0.1:27017" , "value" : null , "errmsg" : "exception: insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.duplicate-key-bug.$_id_ dup key: { : 123 }" , "code" : 11000 , "ok" : 0.0}
- is duplicated by
-
JAVA-517 DuplicateKey exception not properly thrown through findAndModify
- Closed