mongodb - Mongo transactions and updates -
if i've got environment multiple instances of same client connecting mongodb server , want simple locking mechanism ensure single client access short time, can safely use own lock object?
say have 1 object lockstate can "locked" or "unlocked" , plan checks "unlocked" before doing "stuff". lock system say:
db.collection.update( { "lockstate": "unlocked" }, { "lockstate": "locked" })
(aka update lockobj set lockstate = 'locked' lockstate = 'unlocked'
)
if 2 clients try lock system @ same time, possible both clients can end thinking "have lock"?
- both clients find record query parameter of update
- client 1 updates record (which atomic operation)
- update returns success
- client 2 updates document (it's found before client 1 modified it)
- update returns success
i realize contrived case hard reproduce, possible or mongo somehow make client 2's update fail?
alternative approach
use insert instead of update. insert atomic , fail if document exists.
to lock system: db.locks.insert({someid: 27, state: “locked”})
. if insert succeeds - i've got lock , since update atomic, no 1 else can have it. if insert fails - else must have lock.
if 2 clients try lock system @ same time, possible both clients can end thinking "have lock"?
no, 1 client @ time writes lock space (global, database, collection or document depending on version , configuration) , operations on lock space sequential , 1 or other (read or write, not both) per document other connections not mistakenly pick document in inbetween state , think not locked client.
all operations on single document atomic, whether update or insert.