3

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.

neuront
  • 9,312
  • 5
  • 42
  • 71
  • 1
    Why not check if the key is already present first? Instead of managing your flow through exceptions? – Inbar Rose Dec 05 '13 at 09:21
  • 1
    @InbarRose Sometime the key may be not present when checking, but then inserted by another process/thread immediately... – neuront Dec 05 '13 at 09:26
  • That is a totally valid concern (you should explain this in your question). Also, why can't you just access the db using the key you were intending to use originally? the `DuplicateKeyError` means that key is the same, so you already have the key, then you can just access it's value. – Inbar Rose Dec 05 '13 at 09:29
  • @InbarRose sorry I didn't post the actual case at first. I've made some clarification there. – neuront Dec 05 '13 at 09:36

1 Answers1

7

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.

alko
  • 46,136
  • 12
  • 94
  • 102
  • Oops, I hope they bring that to stable release asap. Would you like to share a link about that feature? – neuront Dec 05 '13 at 09:47
  • @neuront no docs for unstable version, so the only link [is source](https://github.com/mongodb/mongo-python-driver/blob/c0614bae1b82dc1b304bf3242e2130e5f52f72ac/pymongo/errors.py#L60) – alko Dec 05 '13 at 09:49
  • Note: In pymongo (3.0+), you can only print `e.message`, unfortunately. – okoboko May 31 '15 at 01:34