PHP, MongoDB, findAndModify


findAndModify is not supported by the current version of the PHP MongoDB driver, so I had to use the following code

$feed = $db->command(array('findAndModify' => 'feedList', 'query' => array('$where' => new MongoCode('
                                 function(){ 
                                      return ((this.inProgress == false)  
                                          || (currentTime >= (this.lastUpdated + this.updateFrequency))));
                                     }', array('currentTime' => $start))), 'update' => array('$set' => array('inProgress' => true))));

Where:

  • $db = Database handle
  • ‘feedList’ = Name of the Collection(Table)
  • inProgress, currentTime,updateFrequency and lastUpdated are some keys
  • $start = a MongoDate Obj

Essentially I am locking a document(set ‘inProgress’ to true) by finding and updating the first document that that is not locked by another process (‘inProgress’ set to false and a few other conditions)

Notice the use of ‘this’ in the MongoCode Obj. I think it refers to the current Document that is being processed.

Also be aware that findAndModify only finds and modifies the first document found.

, , ,

Leave a Reply

Your email address will not be published. Required fields are marked *