关于mongodb更新操作的safe=True参数的问题
我使用 pymongo python 模块工作 mongodb 数据库。我的代码中有一个函数,调用该函数时会更新集合中的记录,如下所示。
for record in coll.find(<some query here>):
#Code here
#...
#...
coll.update({ '_id' : record['_id'] },record)
现在,如果我按如下方式修改代码:
for record in coll.find(<some query here>):
try:
#Code here
#...
#...
coll.update({ '_id' : record['_id'] },record,safe=True)
except:
#Handle exception here
这是否意味着更新失败时会引发异常,或者不会引发异常并且更新只会跳过导致问题的记录?
请帮忙 谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
try
和except
永远不会引发异常。他们只是处理抛出的异常。如果
update
在失败时抛出异常,except
将处理该异常,然后循环将继续(除非您在raise
中使用raise
> except 子句)。如果
update
在失败时不抛出异常,而是返回None
(或类似的内容),并且您希望它抛出异常异常,你可以使用:注意你应该总是指定你想要捕获哪个异常,并且只用
try
包围你想要捕获它的代码行,这样你就不会隐藏其他错误您的代码:请参阅
try
语句,内置异常 和 错误和异常。try
andexcept
never cause an exception to be thrown. They simply handle thrown exceptions.If
update
throws an exception on failure, theexcept
will handle the exception, then the loop will continue (unless you useraise
in theexcept
clause).If
update
doesn't throw an exception on failure, but instead returnsNone
(or something like that), and you want it to throw an exception, you can use:Note you should always specify which exception you want to catch, and only surround the lines of code where you want to catch it with
try
, so you don't hide other errors in your code:See the
try
Statement, Built-in Exceptions, and Errors and Exceptions.使用
safe=True
将导致抛出异常(类型为pymongo.errors.OperationFailure
或子类)(请参阅 pymongo 文档 了解更多信息)如果数据库响应错误。例如,这里我在唯一索引上导致重复键违规:(请注意,
DuplicateKeyError
是OperationFailure
的子类,因此除了OperationFailure:...< /code> 将按预期工作)。
除了
update()
之外,save()
、insert()
和remove()
都接受safe
关键字参数。您还可以在Connection
级别设置safe
,这样您就不必将其包含在每个修改数据库的调用中。Using
safe=True
will cause exceptions (of typepymongo.errors.OperationFailure
or subclasses) to be thrown (see the pymongo docs for more information) if the database responds with an error. For example, here I cause a duplicate key violation on a unique index:(Note that
DuplicateKeyError
is a subclass ofOperationFailure
, soexcept OperationFailure: ...
would work as expected).In addition to
update()
,save()
,insert()
, andremove()
all accept thesafe
keyword argument. You can also setsafe
at theConnection
level, so that you don't have to include it in each call that modifies the database.