获取 DuplicateKeyError 上的重复值 [英] Get the duplicate value on DuplicateKeyError
问题描述
在pymongo中,当DuplicateKeyError
被捕获时,找出异常背后的重复值的正确方法是什么?
In pymongo, when a DuplicateKeyError
caught, what's the proper way to find out the duplicate value behind the the exception?
目前我这样做
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
编辑
这是一个并发应用程序,因此在插入可能失败之前检查重复项.
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.
推荐答案
在 pymongo
(2.7) 的开发版本中,您可以检查 error_document
属性:
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
据我所知,在 2.6 及更早的版本中,除了 error msg
和 code
之外的所有信息都被丢弃了.
As far as I know, in 2.6 and earlier versions, all info except error msg
and code
is discarded.
这篇关于获取 DuplicateKeyError 上的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!