MongoCollection::update PHP Method

update() public method

Update records based on a given criteria
public update ( array $criteria, array $newobj, array $options = [] ) : boolean
$criteria array Description of the objects to update.
$newobj array The object with which to update the matching records.
$options array
return boolean
    public function update(array $criteria, array $newobj, array $options = [])
    {
        $multiple = isset($options['multiple']) ? $options['multiple'] : false;
        $isReplace = !\MongoDB\is_first_key_operator($newobj);
        if ($isReplace && $multiple) {
            throw new \MongoWriteConcernException('multi update only works with $ operators', 9);
        }
        unset($options['multiple']);
        $method = $isReplace ? 'replace' : 'update';
        $method .= $multiple ? 'Many' : 'One';
        try {
            /** @var \MongoDB\UpdateResult $result */
            $result = $this->collection->{$method}(TypeConverter::fromLegacy($criteria), TypeConverter::fromLegacy($newobj), $this->convertWriteConcernOptions($options));
        } catch (\MongoDB\Driver\Exception\Exception $e) {
            throw ExceptionConverter::toLegacy($e);
        }
        if (!$result->isAcknowledged()) {
            return true;
        }
        return ['ok' => 1.0, 'nModified' => $result->getModifiedCount(), 'n' => $result->getMatchedCount(), 'err' => null, 'errmsg' => null, 'updatedExisting' => $result->getUpsertedCount() == 0];
    }

Usage Example

Beispiel #1
0
 /**
  * Zapisuję dokonane zmiany w bazie
  *
  * @return	void
  */
 public function save()
 {
     $aMods = [];
     // dla modelu z modułami
     if ($this->aModules !== null) {
         // obsługa modułów
         foreach ($this->aModules as $mModule) {
             if (!$mModule instanceof Module) {
                 continue;
             }
             $aChanges = $mModule->beforeSave();
             $aMods[] = $mModule;
             if (!empty($aChanges)) {
                 $this->mergeChanges($aChanges);
             }
         }
     }
     $aChanges = $this->getChanges();
     // zapisuję jeśli się coś zmieniło
     if (!empty($aChanges)) {
         $this->oCollection->update(['_id' => $this->getId(true)], $this->getChanges());
         $this->clearChanges();
         // post save
         foreach ($aMods as $oModule) {
             $oModule->afterSave();
         }
     }
 }
All Usage Examples Of MongoCollection::update