Skip to content

Instantly share code, notes, and snippets.

@AndrewDowning
Created February 24, 2013 12:29
Show Gist options
  • Save AndrewDowning/5023641 to your computer and use it in GitHub Desktop.
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.
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