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
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();
         }
     }
 }
 /**
  * Store the api $response as the cached result of the api $request.
  *
  * @param RequestInterface  $request    The request for which the response will be cached.
  * @param ResponseInterface $response   The reponse to cache.
  * @param integer  $timeToLive The time in seconds that the cache should live.
  *
  * @return void
  *
  * @throws \InvalidArgumentException Throw if $timeToLive is not an integer between 0 and 86400.
  */
 public function set(RequestInterface $request, ResponseInterface $response, $timeToLive = null)
 {
     $timeToLive = self::ensureTTL($timeToLive ?: $this->getDefaultTTL());
     $id = $request->getUrl();
     $cache = ['_id' => $id, 'httpCode' => $response->getHttpCode(), 'body' => $response->getBody(), 'headers' => $response->getHeaders(), 'expires' => new \MongoDate(time() + $timeToLive)];
     $this->collection->update(['_id' => $id], $cache, ['upsert' => true]);
 }
 public function update(Kwf_Model_Row_Interface $row, $rowData)
 {
     $ret = $this->_collection->update(array('_id' => $row->_id), $rowData, array('safe' => true, 'multiple' => false));
     if (!$ret || $ret['ok'] != 1) {
         throw new Kwf_Exception("update failed");
     }
 }
 public function addDocument(Document $document)
 {
     $uniqueTokens = array_unique($document->tokens);
     foreach ($uniqueTokens as $token) {
         $this->index->update(["token" => $token], ['$push' => ["documents" => $document->id]], ["upsert" => true]);
     }
 }
 public function updateObject($object, ChangeSet $changeSet)
 {
     $data = $this->prepareUpdateChangeSet($object, $changeSet);
     unset($data['_id']);
     $this->mongoCollection->update($this->getObjectIdentifier($object), array('$set' => $data));
     return $data;
 }
Beispiel #6
0
 /**
  */
 public function add($tokenID)
 {
     $data = array(self::ADDRESS => $this->_encodeRemoteAddress(), self::TID => $tokenID);
     try {
         $this->_db->update($data, array('$set' => array_merge($data, array(self::TIMESTAMP => time()))), array('upsert' => true));
     } catch (MongoException $e) {
         throw new Horde_Token_Exception($e);
     }
 }
Beispiel #7
0
 /**
  * {@inheritdoc }
  */
 public function set($key, $value, $ttl = null)
 {
     $tKey = $this->getKey($key);
     $tValue = $this->pack($value);
     if (!$ttl) {
         $ttl = $this->ttl;
     }
     $item = array('_id' => $tKey, 'value' => $tValue, 'ttl' => $this->getTtl($ttl));
     $this->collection->update(array('_id' => $tKey), $item, array('upsert' => true));
 }
 /**
  * {@inheritdoc}
  */
 public function write($sessionId, $data)
 {
     $data = unserialize($data);
     // we don't save empty sessions
     if (isset($new_data['_sf2_attributes']) && count($new_data['_sf2_attributes']) === 0) {
         return true;
     }
     $this->collection->update(['_id' => $this->encodeSessionId($sessionId)], ['$set' => ['data' => $data, 'expireat' => new \MongoDate(time() + $this->ttl)]], ['upsert' => true, 'multiple' => false]);
     return true;
 }
Beispiel #9
0
 public function update($entity, $options = ['multiple' => true])
 {
     $id = null;
     foreach (['id', '_id'] as $key) {
         if (isset($entity[$key])) {
             $id = (string) $entity[$key];
             unset($entity[$key]);
         }
     }
     $this->collection->update(['_id' => new MongoId($id)], ['$set' => $entity], $options);
 }
Beispiel #10
0
 /**
  * @param string $key Unique key for data that is results of action
  * @param array $data Results of actions
  * @return bool
  */
 public function saveData($key, array $data)
 {
     //@todo Это чтобы гарантировать наличие ключа. Потом возможно заменим это схемой документов
     $data['key'] = $key;
     $status = $this->dataCollection->update(['key' => $key], $data, ['upsert' => true]);
     if ($status['ok'] != 1) {
         $this->logger->error('Node data can not save', ['nodeName' => $this->name, 'dataKey' => $key, 'mongoStatus' => $status]);
         return false;
     }
     $this->logger->info('Node data saved', ['nodeName' => $this->name, 'dataKey' => $key]);
     return true;
 }
Beispiel #11
0
 /**
  * Execute the update query.
  *
  * @see Collection::update()
  * @param array $query
  * @param array $newObj
  * @param array $options
  * @return array|boolean
  */
 protected function doUpdate(array $query, array $newObj, array $options)
 {
     $options = isset($options['safe']) ? $this->convertWriteConcern($options) : $options;
     $options = isset($options['wtimeout']) ? $this->convertWriteTimeout($options) : $options;
     $options = isset($options['timeout']) ? $this->convertSocketTimeout($options) : $options;
     return $this->mongoCollection->update($query, $newObj, $options);
 }
Beispiel #12
0
 /**
  * Save current object to MongoDB
  *
  * @param boolean $refresh Should refresh the object fields values?
  * @return boolean
  */
 function save($refresh = false)
 {
     if (!$this->_collection) {
         import("@.RMongoException");
         throw new RMongoException("Object is not in any collection, please use setCollection() to method to set a collection.");
     }
     $bool = true;
     if ($this->_id) {
         //if exists
         if (!empty($this->_operations)) {
             $bool = $this->_collection->update(array("_id" => $this->_id), $this->_operations, array("upsert" => false, "multiple" => false));
             if ($refresh) {
                 $bool = $this->refresh();
             }
         }
     } else {
         $bool = $this->_collection->insert($this->_attrs, true);
         if ($bool) {
             $this->_id = $this->_attrs["_id"];
             import("@.RMongo");
             RMongo::setLastInsertId($this->_id->__toString());
         }
     }
     $this->_operations = array();
     return $bool;
 }
 /**
  * This writes to memory. 
  * After returning PHP will invoke SessionHandler::close.
  * 
  * @param string $sessionId
  * @param string $data Serialized shit
  * @return boolean
  */
 public function write($sessionId, $data)
 {
     $query = array("session-id" => $sessionId);
     $toSave = array_merge($query, array("data" => $data, "time" => time()));
     try {
         $el = $this->collection->findOne($query);
         if ($el === null) {
             $result = $this->collection->save($toSave);
         } else {
             $result = $this->collection->update($query, $toSave);
         }
         return $result["ok"] == 1;
     } catch (MongoCursorException $ex) {
         return false;
     }
 }
Beispiel #14
0
 /**
  * Write Session - commit data to resource
  *
  * @param string $id
  * @param mixed  $data
  */
 public function write($id, $data)
 {
     try {
         if (empty($_SESSION)) {
             $this->destroy($id);
             return;
         }
         $exists = isset($this->_sessionHashes[$id]);
         $modified = $exists && $this->_sessionHashes[$id] !== md5($data);
         if (!$exists || $modified) {
             $filter = array('_id' => $id);
             $options = array('upsert' => true, 'multiple' => false);
             $update = array('data' => $data, 'metadata.created' => new MongoDate(time()), 'rawData' => $_SESSION);
             if (!$exists) {
                 $update['metadata.expire'] = new MongoDate(time() + $this->_maxLifeTime);
             }
             \App::cache()->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('session'));
             $result = $this->_collection->update($filter, array('$set' => $update), $options);
             if ($result['ok'] == 1) {
                 return true;
             }
         } else {
             return true;
         }
     } catch (Exception $e) {
         \App::log()->crit($e);
     }
     return false;
 }
Beispiel #15
0
 protected function doUpdate($query, array $newObj, array $options)
 {
     if (is_scalar($query)) {
         $query = array('_id' => $query);
     }
     return $this->mongoCollection->update($query, $newObj, $options);
 }
Beispiel #16
0
 /**
  */
 public function store($scope_ob)
 {
     foreach ($scope_ob->getDirty() as $name) {
         $value = $scope_ob->get($name);
         if (is_null($value)) {
             $this->remove($scope_ob->scope, $name);
         } else {
             $query = array(self::NAME => $name, self::SCOPE => $scope_ob->scope, self::UID => $this->_params['user']);
             try {
                 $this->_db->update($query, array_merge($query, array(self::VALUE => new MongoBinData($value, MongoBinData::BYTE_ARRAY))), array('upsert' => true));
             } catch (MongoException $e) {
                 throw new Horde_Prefs_Exception($e);
             }
         }
     }
 }
 public function testUpdateMultiple()
 {
     $this->object->insert(array("x" => 1));
     $this->object->insert(array("x" => 1));
     $this->object->insert(array("x" => 2, "y" => 3));
     $this->object->insert(array("x" => 2, "y" => 4));
     $this->object->update(array("x" => 1), array('$set' => array('x' => "hi")));
     // make sure one is set, one is not
     $this->assertNotNull($this->object->findOne(array("x" => "hi")));
     $this->assertNotNull($this->object->findOne(array("x" => 1)));
     // multiple update
     $this->object->update(array("x" => 2), array('$set' => array('x' => 4)), array("multiple" => true));
     $this->assertEquals(2, $this->object->count(array("x" => 4)));
     $cursor = $this->object->find(array("x" => 4))->sort(array("y" => 1));
     $obj = $cursor->getNext();
     $this->assertEquals(3, $obj['y']);
     $obj = $cursor->getNext();
     $this->assertEquals(4, $obj['y']);
     // check with upsert if there are matches
     $this->object->update(array("x" => 4), array('$set' => array("x" => 3)), array("upsert" => true, "multiple" => true));
     $this->assertEquals(2, $this->object->count(array("x" => 3)));
     $cursor = $this->object->find(array("x" => 3))->sort(array("y" => 1));
     $obj = $cursor->getNext();
     $this->assertEquals(3, $obj['y']);
     $obj = $cursor->getNext();
     $this->assertEquals(4, $obj['y']);
     // check with upsert if there are no matches
     $this->object->update(array("x" => 15), array('$set' => array("z" => 4)), array("upsert" => true, "multiple" => true));
     $this->assertNotNull($this->object->findOne(array("z" => 4)));
     $this->assertEquals(5, $this->object->count());
 }
Beispiel #18
0
 /**
  * Atomically acknowledge and send a message to the queue.
  *
  * @param array $message the message to ack received from get()
  * @param array $payload the data to store in the message to send. Data is handled same way as \MongoCollection::insert()
  * @param int $qTs earliest unix timestamp the message can be retreived.
  * @param float $py priority for order out of get(). 0 is higher priority than 1
  * @param bool $newTimestamp true to give the payload a new timestamp or false to use given message timestamp
  *
  * @return void
  *
  * @throws \InvalidArgumentException $message does not have a field "id" that is a MongoId
  * @throws \InvalidArgumentException $qTs was not an int
  * @throws \InvalidArgumentException $py was not a float
  * @throws \InvalidArgumentException $py is NaN
  * @throws \InvalidArgumentException $newTimestamp was not a bool
  */
 public function ackSend(array $message, array $payload, $qTs = 0, $py = 0.0, $newTimestamp = true)
 {
     $id = null;
     if (array_key_exists('id', $message)) {
         $id = $message['id'];
     }
     if (!$id instanceof \MongoId) {
         throw new \InvalidArgumentException('$message does not have a field "id" that is a MongoId');
     }
     if (!is_int($qTs)) {
         throw new \InvalidArgumentException('$qTs was not an int');
     }
     if (!is_float($py)) {
         throw new \InvalidArgumentException('$py was not a float');
     }
     if (is_nan($py)) {
         throw new \InvalidArgumentException('$py was NaN');
     }
     if ($newTimestamp !== true && $newTimestamp !== false) {
         throw new \InvalidArgumentException('$newTimestamp was not a bool');
     }
     if ($qTs > self::MONGO_INT32_MAX) {
         $qTs = self::MONGO_INT32_MAX;
     } elseif ($qTs < 0) {
         $qTs = 0;
     }
     $toSet = array('payload' => $payload, 'qr' => false, 'rTs' => new \MongoDate(self::MONGO_INT32_MAX), 'qTs' => new \MongoDate($qTs), 'py' => $py);
     if ($newTimestamp) {
         $toSet['ts'] = new \MongoDate();
     }
     //using upsert because if no documents found then the doc was removed (SHOULD ONLY HAPPEN BY SOMEONE MANUALLY) so we can just send
     $this->_collection->update(array('_id' => $id), array('$set' => $toSet), array('upsert' => true));
 }
Beispiel #19
0
 /**
  * Releases any lock that exists on this document.
  *
  * @param object $document
  */
 public function unlock($document)
 {
     $id = $this->uow->getDocumentIdentifier($document);
     $criteria = array('_id' => $this->class->getDatabaseIdentifierValue($id));
     $lockMapping = $this->class->fieldMappings[$this->class->lockField];
     $this->collection->update($criteria, array('$unset' => array($lockMapping['name'] => true)));
     $this->class->reflFields[$this->class->lockField]->setValue($document, null);
 }
Beispiel #20
0
 public function update(Contact $contact)
 {
     try {
         return $this->contactsManagerCollection->update(array('email' => $contact->getEmail()), array('name' => $contact->getName(), 'email' => $contact->getEmail(), 'photo' => $contact->getPhoto()), array('safe' => true));
     } catch (MongoCursorException $e) {
         //log
     }
     return false;
 }
Beispiel #21
0
 function save($values, $options = array())
 {
     br()->log()->writeln('MONGO->SAVE', "QRY");
     br()->log()->writeln($values, "DAT");
     br()->log()->writeln($options, "OPT");
     $result = parent::update($values, $values);
     br()->log()->writeln('Query complete', 'SEP');
     return $result;
 }
Beispiel #22
0
 /**
  * Perform an update query.
  *
  * @param  array  $query
  * @param  array  $options
  * @return int
  */
 protected function performUpdate($query, array $options = [])
 {
     // Update multiple items by default.
     if (!array_key_exists('multiple', $options)) {
         $options['multiple'] = true;
     }
     $wheres = $this->compileWheres();
     $result = $this->collection->update($wheres, $query, true, $options);
     return $result->getModifiedCount();
 }
 public function updateQuote()
 {
     if ($this->getId()) {
         $data = array('state' => $this->getState(), 'items' => $this->getItems(), 'quote_id' => $this->getQuoteId());
         $this->_tblSales->update(array('_id' => new MongoId($this->getId())), array('$set' => $data));
     } else {
         throw new Exception('could not update quote (no id set)');
     }
     return $this;
 }
 /**
  * Will update a document
  * 
  * @param Array $criteria the set of conditions to be met for update
  * @param Array $fields the fields you wish to update
  * @param boolean $safe Will determine if the update is lazy or not
  * @param boolean $upsert If field doesn't exist add it on the fly
  * @param boolean $multiple update multiple matching quieries
  */
 public function update($criteria = array(), $fields = array(), $safe = true, $upsert = true, $multiple = true)
 {
     ValidatorsUtil::isNullOrEmpty($this->_mongoCollection, "Mongo collection isn't valid, have you set a collection?");
     try {
         $this->_mongoCollection->update($criteria, $fields, array("safe" => $safe, "upsert" => $upsert, "multiple" => $multiple));
     } catch (MongoException $e) {
         Logger::log($e);
     }
     $this->_count = 0;
     $this->_id = "";
 }
 /**
  * Converts site.super[{user}] value from MongoId to string.
  *
  * @return void
  */
 public function down()
 {
     $db = \DB::getMongoDB();
     $sites = new MongoCollection($db, 'site');
     $sitesCursor = $sites->find([], ['super' => true]);
     foreach ($sitesCursor as $site) {
         foreach ($site['super'] as $key => $supers) {
             $sites->update(['_id' => $site['_id']], ['$set' => ["super.{$key}.user" => (string) $supers['user']]], ['multiple' => true]);
         }
     }
 }
 public function postUp(Schema $schema)
 {
     $helper = new UpgradeHelper($this->container);
     if ($helper->areProductsStoredInMongo()) {
         $database = $helper->getMongoInstance();
         $versionCollection = new \MongoCollection($database, 'pim_versioning_version');
         foreach ($this->movedEntities as $source => $target) {
             $result = $versionCollection->update(['resourceName' => $source], ['$set' => ['resourceName' => $target]], ['multiple' => true]);
         }
     }
 }
Beispiel #27
0
 /**
  */
 public function write($id, $session_data)
 {
     /* Update/insert session data. */
     try {
         $this->_db->update(array(self::SID => $id), array(self::DATA => new MongoBinData($session_data, MongoBinData::BYTE_ARRAY), self::MODIFIED => time(), self::SID => $id), array('upsert' => true));
         $this->_locked = false;
     } catch (MongoException $e) {
         return false;
     }
     return true;
 }
 /**
  * Convert foreign id values from MongoId to string.
  *
  * @return void
  */
 public function down()
 {
     // The Client model has a mutator that converts lrs_id from string to MongoId,
     // so the Mongo classes are used to directly modify the client collection.
     $db = \DB::getMongoDB();
     $clients = new MongoCollection($db, 'client');
     $lrsIds = $clients->aggregateCursor([['$group' => ['_id' => '$lrs_id']]]);
     foreach ($lrsIds as $lrsId) {
         $clients->update(['lrs_id' => $lrsId['_id']], ['$set' => ['lrs_id' => (string) $lrsId['_id']]], ['multiple' => true]);
     }
     echo 'Foreign id values in client collection converted from MongoId to string.' . PHP_EOL;
 }
Beispiel #29
0
 /**
  * Return indexed keys of requests related with request to parent node
  * @param string $parentRequestKey Ключ запроса к родительскому узлу
  * @return \MongoCursor
  */
 public function getIndexByParent($parentRequestKey)
 {
     $bindList = [];
     $index = $this->indexCollection->find(['parent_request_key' => $parentRequestKey, 'expired' => ['$exists' => 0]]);
     $index->snapshot();
     while ($index->hasNext()) {
         $bindList[] = $index->getNext();
     }
     $this->indexCollection->update(['parent_request_key' => $parentRequestKey], ['$set' => ['expired' => true]], ['multiple' => true]);
     // @todo Тут проблемный момент из-за отсутствия транзакций. Надо эту часть обдумать. Просто могут лишние индексы удалиться.
     return $bindList;
 }
Beispiel #30
0
 /**
  * Perform an update query.
  *
  * @param  array  $query
  * @param  array  $options
  * @return int
  */
 protected function performUpdate($query, array $options = array())
 {
     // Update multiple items by default.
     if (!array_key_exists('multiple', $options)) {
         $options['multiple'] = true;
     }
     $wheres = $this->compileWheres();
     $result = $this->collection->update($wheres, $query, $options);
     if (1 == (int) $result['ok']) {
         return $result['n'];
     }
     return 0;
 }