I'm using pymongo in a web app, and want to do something of the form:
doc = collection.find(document)
doc.array1.append('foo')
for(y in doc.array2): <do things with y>
doc.array2 = filter(lambda x: ..., doc.array2)
doc.x = len(doc.array2)
collection.save(doc)
Is there any simple way way I can handle multiple requests dealing with the same document and prevent one from clobbering the results of another / be made invalid because it's editing a stale version?
Take a look at the section in the mongodb docs on Atomic Operations
The section that might be of interest to you is the part about updating if it is still current.
- Fetch the object.
- Modify the object locally.
- Send an update request that says "update the object to this new value if it still matches its old value".
Should the operation fail, we might then want to try again from step 1.
This is the approach for when you have a number of operations to perform and you want to avoid holding a lock on the database. They also state in that doc how they are generally against holding a lock.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With