Created
February 24, 2013 12:29
-
-
Save AndrewDowning/5023641 to your computer and use it in GitHub Desktop.
MongoDB doing find_and_modify, allowing for possible operation failure and auto reconnections.
This example shows using find_and_modify to run a counter on a document that may not initially exist.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import pymongo | |
from pymongo import Connection | |
def safe_modify(col, query, update): | |
for attempt in range(5): | |
try: | |
result = col.find_and_modify(query={'name': 'Andrew'}, | |
update={"$inc": {"count": 1}}, | |
upsert=True, # If document for 'name':'Andrew' not in there, make one. | |
new=True) # Return the updated result. | |
return result | |
except pymongo.errors.OperationFailure: | |
return False | |
except pymongo.errors.AutoReconnect as _e: | |
wait_t = 0.5 * pow(2, attempt) | |
time.sleep(wait_t) | |
return False | |
countercol = Connection().counterdb.countercol | |
#countercol.drop() # Uncomment once to see it go back to empty and start from count=0 | |
result = safe_modify(countercol, {'name': 'Andrew'}, {"$inc": {"count": 1}}) | |
print(result['count']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment