Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...