Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locking a document in MongoDB

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?

like image 463
James Harcourt Avatar asked May 10 '26 23:05

James Harcourt


1 Answers

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.

  1. Fetch the object.
  2. Modify the object locally.
  3. 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.

like image 108
jdi Avatar answered May 14 '26 01:05

jdi