有关用于mongodb更新操作的safe = True参数的问题 [英] Question about safe=True parameter for update operation of mongodb

查看:514
本文介绍了有关用于mongodb更新操作的safe = True参数的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用pymongo python模块处理mongodb数据库.我的代码中有一个函数,调用该函数时,将更新集合中的记录,如下所示.

Im working a mongodb database using pymongo python module. I have a function in my code which when called updates the records in the collection as follows.

for record in coll.find(<some query here>):
   #Code here
   #...
   #...
   coll.update({ '_id' : record['_id'] },record)

现在,如果我按如下所示修改代码:

Now, if i modify the code as follows :

for record in coll.find(<some query here>):
   try:
       #Code here
       #...
       #...
       coll.update({ '_id' : record['_id'] },record,safe=True)
   except:
        #Handle exception here

这是否意味着在更新失败时将引发异常,或者将不引发异常并且更新将仅跳过引起问题的记录?

Does this mean an exception will be thrown when update fails or no exception will be thrown and update will just skip the record causing a problem ?

请帮助 谢谢

推荐答案

使用safe=True会引发异常(类型为pymongo.errors.OperationFailure或子类)(请参阅

Using safe=True will cause exceptions (of type pymongo.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:

>>> db.bar.insert({'a': 1, 'b': 1})
ObjectId('4e4bc586c67f060b25000000')
>>> db.bar.ensure_index('a', unique=True)
u'a_1'
>>> db.bar.insert({'a': 2, 'b': 1}, safe=True)
ObjectId('4e4bc71fc67f060b25000003')
>>> db.bar.update({'a': 2}, {'a': 1}, safe=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/pymongo/collection.py", line 368, in update
    spec, document, safe, kwargs), safe)
  File "/Library/Python/2.7/site-packages/pymongo/connection.py", line 770, in _send_message
    return self.__check_response_to_last_error(response)
  File "/Library/Python/2.7/site-packages/pymongo/connection.py", line 718, in __check_response_to_last_error
    raise DuplicateKeyError(error["err"])
pymongo.errors.DuplicateKeyError: E11000 duplicate key error index: test.bar.$a_1  dup key: { : 1 }

(请注意,DuplicateKeyErrorOperationFailure的子类,因此except OperationFailure: ...将按预期工作).

(Note that DuplicateKeyError is a subclass of OperationFailure, so except OperationFailure: ... would work as expected).

除了update()之外,save()insert()remove()都接受safe关键字参数.您还可以在Connection级别上设置safe,这样就不必在每次修改数据库的调用中都包含它.

In addition to update(), save(), insert(), and remove() all accept the safe keyword argument. You can also set safe at the Connection level, so that you don't have to include it in each call that modifies the database.

这篇关于有关用于mongodb更新操作的safe = True参数的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆