0

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

  • What do you think you mean by "cluster"? MongoDB has Replica Sets out of which only one node is ever written to at any time. There are also "shards" of which only a partition of the data is present on any given shard configuration at a time. Why are you even using MongoDB 2.4, which is long past end of life for support? Or are you actually referring to the version of the driver version? ( C# happens to be at 2.4 at present ) – Neil Lunn Aug 31 '17 at 10:08
  • Yes, the technology is a constraint of the solution at this stage. It is mongodb 2.4 on a replica set. Will findAndModify still keep the atomicity over the replica set? – Giancarlo Sanchez Aug 31 '17 at 10:13
  • You are only ever writing to one node. You cannot possibly write to more that one node. Therefore logically why would there be any difference? Trying to appeal to a sense of reasoning here. You would be strongly advised to upgrade those nodes as soon as possible. Things develop and bugs get fixed. You really don't want to be left dragging so far behind. – Neil Lunn Aug 31 '17 at 10:15
  • Sorry, perhaps I did not explain correctly. The version is not the question itself and we are working towards migrating to mongo 3+ but it is outside my reach of action. The real questios is if I can simulate a sync lock using findAndModify in a replica set? I updated with some sample code I'm using – Giancarlo Sanchez Aug 31 '17 at 10:37

0 Answers0