Question about safe = True parameter for mongodb update operation

Im working with mongodb database using pythongo python module. I have a function in my code that, when called, updates the entries in the collection as follows.

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

Now, if I change 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 that an exception will be thrown when the update fails, or an exception will not be thrown, and the update will simply skip the record, causing the problem?

Please help thank you

+4
source share
2 answers

try and except never throw an exception. They simply handle thrown exceptions.

If update throws an exception on error, except will handle the exception, then the loop will continue (unless you use raise in the except clause).

If update does not throw an exception on failure, but instead returns None (or something like that), and you want to throw an exception, you can use:

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

Note that you should always indicate which exception you want to catch, and surround only lines of code where you want to catch it with try , so you do not hide other errors in your code:

 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 

See try Statement , Built-in Exceptions and Errors and Exceptions .

+3
source

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.

+3
source

All Articles