Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the duplicate value on DuplicateKeyError

In pymongo, when a DuplicateKeyError caught, what's the proper way to find out the duplicate value behind the the exception?

Currently I do this

try:
    db.coll.insert({key: ['some_value', 'some_value_1']})
except pymongo.errors.DuplicateKeyError, e:
    dups = re.findall(r'\{\ +:\ +"(.*)"\ +\}$', e.message)
    if len(dups) == 1:
        print dups[0]

It seems to work, but is there any easier way, like

try:
    db.coll.insert({key: ['some_value', 'some_value_1']})
except pymongo.errors.DuplicateKeyError, e:
    print e.dup_val

EDIT

It's a concurrent app, so check duplicates before insert might fail.

The field is an array, so it's hard to find out which one is the duplicate value.

like image 499
neuront Avatar asked May 15 '26 22:05

neuront


1 Answers

In dev version of pymongo (2.7) you can check with error_document property:

try:
    db.coll.insert({name: 'some_value'})
except pymongo.errors.DuplicateKeyError, e:
    print e.error_document

As far as I know, in 2.6 and earlier versions, all info except error msg and code is discarded.

like image 122
alko Avatar answered May 17 '26 13:05

alko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!