/** * Write into database * * @param $collection * @param $command * @param $data * @return mixed */ public function write($collection, $command, $data) { // Make sure the database is connected $this->_connection or $this->connect(); // Set the last query $this->_last_query = $data; // Configurations $config = $this->_config; // Exec bulk command $bulk = new BulkWrite(); switch ($command) { case 'insert': $data['_id'] = new \MongoDB\BSON\ObjectID(); $bulk->insert($data); break; case 'update': $bulk->update($data[0], $data[1], $data[2]); break; case 'delete': $bulk->delete($data[0], $data[1]); break; } try { $writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000); $response = $this->_connection->executeBulkWrite($config['database'] . '.' . $collection, $bulk, $writeConcern); } catch (\MongoDB\Driver\Exception\BulkWriteException $e) { //print_r($e);die(); echo $e->getMessage(), "\n"; //exit; } return $response; }
public function update($myNamespace, $data, $id) { $result = []; $collection = $this->getCollection($myNamespace); $id = new ObjectID($id); unset($data->_id); $bulk = new BulkWrite(); $bulk->update(['_id' => $id], $data); $this->manager->executeBulkWrite($myNamespace, $bulk); //delete unset value //$result = $collection->updateOne(['_id'=>$id],['$set'=>$data]);//keep unset value return $result; }
/** * Execute commands batch (bulk). * @param string $collectionName collection name. * @param array $options batch options. * @return array array of 2 elements: * * - 'insertedIds' - contains inserted IDs. * - 'result' - [[\MongoDB\Driver\WriteResult]] instance. * * @throws Exception on failure. * @throws InvalidConfigException on invalid [[document]] format. */ public function executeBatch($collectionName, $options = []) { $databaseName = $this->databaseName === null ? $this->db->defaultDatabaseName : $this->databaseName; $token = $this->log([$databaseName, $collectionName, 'bulkWrite'], $this->document, __METHOD__); try { $this->beginProfile($token, __METHOD__); $batch = new BulkWrite($options); $insertedIds = []; foreach ($this->document as $key => $operation) { switch ($operation['type']) { case 'insert': $insertedIds[$key] = $batch->insert($operation['document']); break; case 'update': $batch->update($operation['condition'], $operation['document'], $operation['options']); break; case 'delete': $batch->delete($operation['condition'], isset($operation['options']) ? $operation['options'] : []); break; default: throw new InvalidConfigException("Unsupported batch operation type '{$operation['type']}'"); } } $this->db->open(); $server = $this->db->manager->selectServer($this->getReadPreference()); $writeResult = $server->executeBulkWrite($databaseName . '.' . $collectionName, $batch, $this->getWriteConcern()); $this->endProfile($token, __METHOD__); } catch (RuntimeException $e) { $this->endProfile($token, __METHOD__); throw new Exception($e->getMessage(), $e->getCode(), $e); } return ['insertedIds' => $insertedIds, 'result' => $writeResult]; }
/** * Execute the operation. * * @see Executable::execute() * @param Server $server * @return BulkWriteResult */ public function execute(Server $server) { $bulk = new Bulk(['ordered' => $this->options['ordered']]); $insertedIds = []; foreach ($this->operations as $i => $operation) { $type = key($operation); $args = current($operation); switch ($type) { case self::DELETE_MANY: case self::DELETE_ONE: $bulk->delete($args[0], $args[1]); break; case self::INSERT_ONE: $insertedId = $bulk->insert($args[0]); if ($insertedId !== null) { $insertedIds[$i] = $insertedId; } else { // TODO: This may be removed if PHPC-382 is implemented $insertedIds[$i] = is_array($args[0]) ? $args[0]['_id'] : $args[0]->_id; } break; case self::REPLACE_ONE: case self::UPDATE_MANY: case self::UPDATE_ONE: $bulk->update($args[0], $args[1], $args[2]); } } $writeConcern = isset($this->options['writeConcern']) ? $this->options['writeConcern'] : null; $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $writeConcern); return new BulkWriteResult($writeResult, $insertedIds); }
/** * 指定字段的值-1 * * @param string $key 操作的key user-id-1 * @param int $val * @param string $field 要改变的字段 * * @return bool */ public function decrement($key, $val = 1, $field = null) { list($tableName, $condition) = $this->parseKey($key, true); if (is_null($field) || empty($tableName) || empty($condition)) { $this->bindParams = array(); return false; } $val = abs(intval($val)); $tableName = $this->tablePrefix . $tableName; $bulk = new BulkWrite(); $bulk->update($condition, array('$inc' => array($field => -$val)), array('multi' => true)); $result = $this->runMongoBulkWrite($tableName, $bulk); $GLOBALS['debug'] && $this->debugLogSql('BulkWrite DEC', $this->tablePrefix . $tableName, $condition, array('$inc' => array($field => -$val))); return $result->getModifiedCount(); }
/** * Execute the operation. * * @see Executable::execute() * @param Server $server * @return UpdateResult */ public function execute(Server $server) { $options = array('multi' => $this->options['multi'], 'upsert' => $this->options['upsert']); $bulk = new Bulk(); $bulk->update($this->filter, $this->update, $options); $writeConcern = isset($this->options['writeConcern']) ? $this->options['writeConcern'] : null; $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $writeConcern); return new UpdateResult($writeResult); }
/** * Execute the operation. * * @see Executable::execute() * @param Server $server * @return BulkWriteResult */ public function execute(Server $server) { $options = ['ordered' => $this->options['ordered']]; if (isset($this->options['bypassDocumentValidation']) && \MongoDB\server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)) { $options['bypassDocumentValidation'] = $this->options['bypassDocumentValidation']; } $bulk = new Bulk($options); $insertedIds = []; foreach ($this->operations as $i => $operation) { $type = key($operation); $args = current($operation); switch ($type) { case self::DELETE_MANY: case self::DELETE_ONE: $bulk->delete($args[0], $args[1]); break; case self::INSERT_ONE: $insertedId = $bulk->insert($args[0]); if ($insertedId !== null) { $insertedIds[$i] = $insertedId; } else { $insertedIds[$i] = \MongoDB\extract_id_from_inserted_document($args[0]); } break; case self::REPLACE_ONE: case self::UPDATE_MANY: case self::UPDATE_ONE: $bulk->update($args[0], $args[1], $args[2]); } } $writeConcern = isset($this->options['writeConcern']) ? $this->options['writeConcern'] : null; $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $writeConcern); return new BulkWriteResult($writeResult, $insertedIds); }
/** * Updates documents in collection * * @param array $query * @param array $action * * @return Result */ public function update($query, $action) { $result = new Result(); $bulk = new BulkWrite(); $bulk->update($query, $action, ['multi' => 1]); $dbResult = $this->executeBulkWrite($bulk); if ($dbResult instanceof Exception) { $result->setError(Result::ERROR_CANNOT_UPDATE_RECORD, $dbResult->getMessage()); } return $result; }
public function update($namespace, $query = [], $update = [], $options = []) { $bulk = new BulkWrite(); $bulk->update($query, $update, $options); $this->result = $this->write($namespace, $bulk); return !$this->result->getWriteErrors(); }
/** * Execute the operation. * * @see Executable::execute() * @param Server $server * @return UpdateResult */ public function execute(Server $server) { $updateOptions = ['multi' => $this->options['multi'], 'upsert' => $this->options['upsert']]; $bulkOptions = []; if (isset($this->options['bypassDocumentValidation']) && \MongoDB\server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)) { $bulkOptions['bypassDocumentValidation'] = $this->options['bypassDocumentValidation']; } $bulk = new Bulk($bulkOptions); $bulk->update($this->filter, $this->update, $updateOptions); $writeConcern = isset($this->options['writeConcern']) ? $this->options['writeConcern'] : null; $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $writeConcern); return new UpdateResult($writeResult); }
/** * 指定字段的值-1 * * @param string $key 操作的key user-id-1 * @param int $val * @param string $field 要改变的字段 * @param mixed $tablePrefix 表前缀 不传则获取配置中配置的前缀 * * @return bool */ public function decrement($key, $val = 1, $field = null, $tablePrefix = null) { list($tableName, $condition) = $this->parseKey($key, true); if (is_null($field) || empty($tableName) || empty($condition)) { return false; } $val = abs(intval($val)); is_null($tablePrefix) && ($tablePrefix = $this->tablePrefix); $tableName = $tablePrefix . $tableName; $bulk = new BulkWrite(); $bulk->update($condition, ['$inc' => [$field => -$val]], ['multi' => true]); $result = $this->runMongoBulkWrite($tableName, $bulk); Cml::$debug && $this->debugLogSql('BulkWrite DEC', $tableName, $condition, ['$inc' => [$field => -$val]]); return $result->getModifiedCount(); }
public function updateAndReturnNonexistantIds($ids, $update_definition) { $bulk = new MongoDB\Driver\BulkWrite(['ordered' => false]); foreach ($ids as $id) { $bulk->update(["_id" => $id], $update_definition, ["limit" => 0, "upsert" => false, "multi" => false]); } $result = $this->mongo_manager->executeBulkWrite($this->databaseAndCollectionName(), $bulk, $this->write_concern); if (count($ids) > $result->getModifiedCount()) { $query = new MongoDB\Driver\Query(['_id' => ['$in' => $ids]]); $result = $this->mongo_manager->executeQuery($this->databaseAndCollectionName(), $query); //print_r($result->toArray()); $result_ids = []; collect($result->toArray())->each(function ($result) use(&$result_ids) { //Why does it return stdclass? grr $result = get_object_vars($result); echo "pushing" . $result['_id'] . "\n"; array_push($result_ids, $result['_id']); }); echo "result_ids: "; var_dump($result_ids); echo "\narray diff:\n"; var_dump(array_diff($ids, $result_ids)); } }
function updateManyDocumentsDemo() { $bulk = new MongoDB\Driver\BulkWrite(['ordered' => false]); //limit: limit the number of documents matched and updated to the specified value or unlimited when 0 //You can also use something like ["viking" => "false"] for the first (filter) line $bulk->update(["_id" => ['$in' => ["1001", "1002"]]], ['$inc' => ["days.01.views" => 1]], ["limit" => 0, "upsert" => false, "multi" => true]); try { $result = $this->mongo_manager->executeBulkWrite("db.collection", $bulk, $this->write_concern); var_dump($result); } catch (MongoDB\Driver\Exception\Exception $e) { echo $e->getMessage(), "\n"; } }
/** * {@inheritdoc} */ protected function performRollback($table, array $records) { $bulk = new BulkWrite(); foreach ($records as $record) { $id = $record['_id']; unset($record['_id']); $record['status'] = 'ROLLBACK'; $bulk->update(array('_id' => $id), array('$set' => $record)); } $this->conn->executeBulkWrite($this->getNamespace($table), $bulk); }
/** * update data to database * @param array $data the formatede array for database * @return void */ public function update($entity) { try { $data = $entity->toArray(); $this->updateEmbedded($data, $entity); $theId = new MongoId($data['_id']); unset($data['_id']); $this->callBehavior('beforeUpdate', $data, $entity); $bulk = new BulkWrite(); $bulk->update(['_id' => $theId], $data); $this->manager->executeBulkWrite($this->dbName . '.' . $this->collectionName, $bulk); $this->callBehavior('afterUpdate', $data, $entity); } catch (Exception $e) { throw $e; } }
/** * Creates/Updates a collection based on the values in the atributes * * @param array $filter * @param array $options * @return boolean * @throws Exception */ public function update($filter = [], $options = []) { if (!is_array($filter)) { throw new Exception('The "filter" must be an array !'); } if (!is_array($options)) { throw new Exception('The "options" must be an array !'); } $db = $this->getDB(); $source = $this->getSource(); if (empty($source)) { throw new Exception('Method getSource() returns empty string'); } $update = $this->toArray(); if (empty($options)) { $options = ['limit' => 0, 'upsert' => false]; } $bulk = new BulkWrite(); $bulk->update($filter, $update, $options); $result = $this->getCollectionManager()->executeBulkWrite($this, $db, $source, $bulk); if (empty($result->getWriteErrors())) { return true; } else { return false; } return false; }