MongoDB findAndModify is atomic in a cluster?

161 Views Asked by At

I'm implementing a solution which uses MongoDB findAndModify to simulate resource locks.

My question is, does findAndModify offer the same atomicity over replica set as it does on a single instance?

This is a sample PHP code

$lock = $this->getMongoDb()->selectCollection('users')->findAndModify(
             array(
                        '_id' => new MongoId($id),
                        '$or'                       => array(
                            array('transaction.locked' => array('$ne'=>true)),
                            array('transaction.locked' => true, 'transaction.timestamp' => array('$lt' => new MongoDate(strtotime($lock_timeout))))
                        )
                ),
             array(
                        '$set' => array(
                                    'transaction.locked' => true,
                                    "transaction.timestamp" => new MongoDate(strtotime($current_time))
                                )
                )
        );

I create a lock by checking that the record exists and is not locked, for which then the record is locked.

If I attempt to execute this against a replica set multiple times simultaneously, will the findAndModify still work as a sync lock by just allowing the very first call to succeed?

Thanks

0

There are 0 best solutions below