python - 关于mongodb更新操作参数safe=True的问题

标签 python mongodb pymongo

我正在使用 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

这是否意味着更新失败时会抛出异常,或者不会抛出异常,更新只会跳过导致问题的记录?

请帮忙 谢谢

最佳答案

tryexcept 永远不会引发异常。它们只是处理抛出的异常。

如果 update 在失败时抛出异常,except 将处理该异常,然后循环将继续(除非您在中使用 raise except 子句)。

如果 update 没有在失败时抛出异常,而是返回 None(或类似的东西),而您想要它要抛出异常,您可以使用:

if coll.update(...) is None: # or whatever it returns on failure
    raise ValueError # or your custom Exception subclass

请注意,您应该始终指定要捕获的异常,并且只用 try 将要捕获的代码行包围起来,这样您就不会在代码中隐藏其他错误:

for record in coll.find(<some query here>):
   #Code here
   #...
   #...
   try:
       coll.update({ '_id' : record['_id'] },record,safe=True)
   except SpecificException:
        #Handle exception here
   except OtherSpecificException:
        #Handle exception here
   else:
        #extra stuff to do if there was no exception

参见 try Statement , Built-in Exceptions , 和 Errors and Exceptions .

关于python - 关于mongodb更新操作参数safe=True的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7092407/

相关文章:

python - 使用FunctionalAPI 时如何装饰我的枚举?

python - 在 mongoDB 聚合中的 $match 中使用 $cond

python - 当 MongoDB 用作数据库时使用哪个 python web 框架(django 或 django-norel 或 Pyramid )

python-3.x - 如何使用 postman 发送发布请求,同时保存到 Mongo 数据库?

python - 尝试使用 python 连接到 mongodb atlas 时连接超时

python - 如何从 Flask 中的表单获取多个选定项目

python - 如何在 Tkinter 中对小部件进行分层(在图像前面制作形状)?

mongodb - 使用 mgo 将数据插入 MongoDB

python - 何时断开与 mongodb 的连接

python - MongoDB 最近 30 天的数据