Using safe=True will throw exceptions (like pymongo.errors.OperationFailure or subclasses) (see pymongo docs for more information) if the database responds with an error. For example, here I cause a duplicate key violation in 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 }
(Note that DuplicateKeyError is a subclass of OperationFailure , so except OperationFailure: ... will work as expected).
In addition to update() , save() , insert() and remove() all accept the safe keyword argument. You can also set safe at the Connection level, so you do not need to include it in every call that modifies the database.
source share