Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pymongo: How to check if the update was successful ?

How to check if the update was successful in Pymongo? If the record was updated with the same value it should be considered a successful update. ie, Even if the modified count is zero it is considered a successful update. How to do this.

result = _db.testcollection.update_one({"_id": col_id}, {"$set": obj})
return True if result.modified_count > 0 else False

This works well if the value is changed. But I want to return true even when technically the record was not changed because the record is same what we are trying to update.

How to do this?

like image 288
Codeformer Avatar asked May 15 '17 04:05

Codeformer


1 Answers

The below solution worked for me.Check matched_count instead of modified_count. If there were a matched records and no exception it means that it is successful.

try:
    result = _db.testcollection.update_one({"_id": col_id}, {"$set": obj})
    return result.matched_count > 0 
except:pymongo.errors.PyMongoError as e:
    return False
like image 132
Codeformer Avatar answered Nov 14 '22 21:11

Codeformer