Uploaded image for project: 'Java Driver'
  1. Java Driver
  2. JAVA-1821

findAndModify() with upsert throws wrong exception for duplicate key errors

    • Type: Icon: Bug Bug
    • Resolution: Won't Fix
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 2.13.1
    • 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}
      

        1. DuplicateKeyBug.java
          1 kB
          Ivan Todoroski

            Assignee:
            Unassigned Unassigned
            Reporter:
            ivan.todoroski Ivan Todoroski
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: