Mongo数据库update操作有一个相对于Mysql的关键特性,它可以使用upsert模式,当更新的数据不存在时,直接插入,但是ThinkPHP的Mongo驱动居然不支持这一特性,没办法,自力更生了。

ThinkPHP的driver层,见由于支持多种DB,又使用了继承,使用得类层次结构较深,负责Mongo驱动的是DbMongo.class.php,文件位于ThinkPHPExtendDriverDb,修改Update方法的$options参数,如果update方法提供了upsert选项时,就以upsert模式更新MongoDB。

   1:  public function update($data,$options) {
   2:          if(isset($options['table'])) {
   3:              $this->switchCollection($options['table']);
   4:          }
   5:          $this->model  =   $options['model'];
   6:          N('db_write',1);
   7:          $query   = $this->parseWhere($options['where']);
   8:          $set  =  $this->parseSet($data);
   9:          $isUpsert = $options['upsert'] === true ? true : false;
  10:          if($this->debug) {
  11:              $this->queryStr   =  $this->_dbName.'.'.$this->_collectionName.'.update(';
  12:              $this->queryStr   .= $query?json_encode($query):'{}';
  13:              $this->queryStr   .=  ','.json_encode($set).')';
  14:          }
  15:          try{
  16:              // 记录开始执行时间
  17:              G('queryStartTime');
  18:              $result   = $this->_collection->update($query,$set,array("upsert" => $isUpsert, "multiple" => true));
  19:              $this->debug();
  20:              return $result;
  21:          } catch (MongoCursorException $e) {
  22:              throw_exception($e->getMessage());
  23:          }
  24:      }