public function insert(array $data) { $result = $this->collection->insertOne($data); $id = (string) $result->getInsertedId(); $data['id'] = $id; return $data; }
/** * @param string $identity * @param Document $document * @return void */ public function upsert(string $identity, Document $document) { $converted = $this->converter->objectToArray($document); if ($this->collection->count([$this->identityField => $identity]) > 0) { $this->collection->replaceOne([$this->identityField => $identity], $converted); } else { $this->collection->insertOne($converted); } }
/** * @see DataModelInterface::create */ public function create($book, $id = null) { $this->verifyBook($book); if ($id) { $book['_id'] = $id; } $result = $this->db->insertOne($book); return $result->getInsertedId(); }
/** * @param object $model * @param array $options * * @return \MongoDB\InsertOneResult */ public function insert($model, array $options = []) { $values = get_object_values($model); $result = $this->collection->insertOne($values, $options); if (false == $result->isAcknowledged()) { throw new \LogicException('Operation is not acknowledged'); } $this->hydrator->hydrate($values, $model); set_object_id($model, $result->getInsertedId()); return $result; }
/** * @param Persistable $model * @param array $options * * @return \MongoDB\InsertOneResult */ public function insert(Persistable $model, array $options = []) { $bson = $model->bsonSerialize(); $result = $this->collection->insertOne($bson, $options); if (false == $result->isAcknowledged()) { throw new \LogicException('Operation is not acknowledged'); } $bson['_id'] = (string) $result->getInsertedId(); $this->hydrator->hydrate($bson, $model); return $result; }
public function testSeeElementIsObjectThrowsError() { $trumpet = new \StdClass(); $trumpet->name = 'Trumpet 1'; $trumpet->pitch = 'B♭'; $trumpet->price = array('min' => 458, 'max' => 891); $this->setExpectedException('PHPUnit_Framework_ExpectationFailedException'); $this->userCollection->insertOne(array('id' => 5, 'trumpet' => $trumpet)); $this->userCollection->insertOne(array('id' => 6, 'trumpet' => $trumpet)); $this->module->seeElementIsObject('users', array(), 'trumpet'); }
/** * Inserts an array into the collection * * @link http://www.php.net/manual/en/mongocollection.insert.php * @param array|object $a * @param array $options * @throws MongoException if the inserted document is empty or if it contains zero-length keys. Attempting to insert an object with protected and private properties will cause a zero-length key error. * @throws MongoCursorException if the "w" option is set and the write fails. * @throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds. * @return bool|array Returns an array containing the status of the insertion if the "w" option is set. */ public function insert(&$a, array $options = []) { if (!$this->ensureDocumentHasMongoId($a)) { trigger_error(sprintf('%s expects parameter %d to be an array or object, %s given', __METHOD__, 1, gettype($a)), E_WARNING); return; } $result = $this->collection->insertOne(TypeConverter::fromLegacy($a), $this->convertWriteConcernOptions($options)); if (!$result->isAcknowledged()) { return true; } return ['ok' => 1.0, 'n' => 0, 'err' => null, 'errmsg' => null]; }
/** * Limit is in seconds * * @param string $id * @param int $limit */ public function lock($id, $limit = 300) { // I think it must be a bit greater then mongos index ttl so there is a way to process data. $timeout = time() + $limit; while (time() < $timeout) { try { $result = $this->collection->insertOne(['_id' => new ObjectID((string) $id), 'timestamp' => new UTCDatetime(time() * 1000), 'sessionId' => $this->sessionId]); if (false == $result->isAcknowledged()) { throw new \LogicException(sprintf('Cannot obtain the lock for id %s. The insertOne operation is not acknowledged.', $id)); } return; } catch (BulkWriteException $e) { } catch (DuplicateKeyException $e) { // The lock is obtained by another process. Let's try again later. } // Mongo does database lock level on insert, so everything has to wait even reads. // I decided to do it rarely to decrease global lock rate. // We will have at least 150 attempts to get the lock, pretty enough IMO. // More here http://docs.mongodb.org/manual/faq/concurrency/ usleep(200000); } throw new \RuntimeException(sprintf('Cannot obtain the lock for id "%s". Timeout after %s seconds', $id, $limit)); }
public function insertMany(array $documents, array $options = []) { $textDoc = json_encode($documents); $textOptions = json_encode($options); $collectionName = $this->collection->getCollectionName(); Yii::trace("Executing insertMany: {\$document: {$textDoc}, \$options: {$textOptions} }", "mongoyii\\Collection"); if ($this->client->enableProfiling) { Yii::beginProfile("mongoyii\\{$collectionName}.insertMany({\$document: {$textDoc}, \$options: {$textOptions} })", 'mongoyii\\Collection.insertMany'); } $res = $this->collection->insertOne($documents, $options); if ($this->client->enableProfiling) { Yii::endProfile("mongoyii\\{$collectionName}.insertMany({\$document: {$textDoc}, \$options: {$textOptions} })", 'mongoyii\\Collection.insertMany'); } return $res; }
/** * Send a message to the queue. * * @param array $payload the data to store in the message. Data is handled same way as \MongoDB\Collection::insertOne() * @param int $earliestGet earliest unix timestamp the message can be retreived. * @param float $priority priority for order out of get(). 0 is higher priority than 1 * * @return void * * @throws \InvalidArgumentException $earliestGet was not an int * @throws \InvalidArgumentException $priority was not a float * @throws \InvalidArgumentException $priority is NaN */ public function send(array $payload, $earliestGet = 0, $priority = 0.0) { if (!is_int($earliestGet)) { throw new \InvalidArgumentException('$earliestGet was not an int'); } if (!is_float($priority)) { throw new \InvalidArgumentException('$priority was not a float'); } if (is_nan($priority)) { throw new \InvalidArgumentException('$priority was NaN'); } //Ensure $earliestGet is between 0 and MONGO_INT32_MAX $earliestGet = min(max(0, $earliestGet * 1000), self::MONGO_INT32_MAX); $message = ['payload' => $payload, 'running' => false, 'resetTimestamp' => new \MongoDB\BSON\UTCDateTime(self::MONGO_INT32_MAX), 'earliestGet' => new \MongoDB\BSON\UTCDateTime($earliestGet), 'priority' => $priority, 'created' => new \MongoDB\BSON\UTCDateTime((int) (microtime(true) * 1000))]; $this->collection->insertOne($message); }
/** * Inserts an array into the collection * * @link http://www.php.net/manual/en/mongocollection.insert.php * @param array|object $a * @param array $options * @throws MongoException if the inserted document is empty or if it contains zero-length keys. Attempting to insert an object with protected and private properties will cause a zero-length key error. * @throws MongoCursorException if the "w" option is set and the write fails. * @throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds. * @return bool|array Returns an array containing the status of the insertion if the "w" option is set. */ public function insert(&$a, array $options = []) { if (!$this->ensureDocumentHasMongoId($a)) { trigger_error(sprintf('%s(): expects parameter %d to be an array or object, %s given', __METHOD__, 1, gettype($a)), E_USER_WARNING); return; } if (!count((array) $a)) { throw new \MongoException('document must be an array or object'); } try { $result = $this->collection->insertOne(TypeConverter::fromLegacy($a), $this->convertWriteConcernOptions($options)); } catch (\MongoDB\Driver\Exception\Exception $e) { throw ExceptionConverter::toLegacy($e); } if (!$result->isAcknowledged()) { return true; } return ['ok' => 1.0, 'n' => 0, 'err' => null, 'errmsg' => null]; }
/** * @param EventDescriptor $event * @return bool */ public function append(EventDescriptor $event) : bool { $eventData = $event->toArray(); $result = $this->collection->insertOne($eventData); return $result->isAcknowledged(); }
/** * Inserts an array into the collection * @link http://www.php.net/manual/en/mongocollection.insert.php * @param array|object $a * @param array $options * @throws MongoException if the inserted document is empty or if it contains zero-length keys. Attempting to insert an object with protected and private properties will cause a zero-length key error. * @throws MongoCursorException if the "w" option is set and the write fails. * @throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds. * @return bool|array Returns an array containing the status of the insertion if the "w" option is set. */ public function insert($a, array $options = array()) { return $this->collection->insertOne(TypeConverter::convertLegacyArrayToObject($a), $options); }
/** * Insert a new record and get the value of the primary key. * * @param array $values * @param string $sequence * @return int */ public function insertGetId(array $values, $sequence = null) { $result = $this->collection->insertOne($values); return $result->getInsertedId(); }
/** * @param string $sagaType * @param string $identity * @param array $associationValues * @param string $data * @return void */ public function insert(string $sagaType, string $identity, array $associationValues, string $data) { $sagaData = ['type' => $sagaType, 'identity' => $identity, 'associations' => $associationValues, 'serialized' => $data]; $this->collection->insertOne($sagaData); }
/** * @param Result $result * @return \MongoDB\InsertOneResult */ public function save(Result $result) { $document = ['url' => $result->getUrl(), 'modifiedSince' => $result->getModifiedSince(), 'feed' => $result->getFeed()->toArray()]; return $this->collection->insertOne($document); }
/** * {@inheritdoc} */ public function insertOne($document, array $options = []) { $event = $this->startQueryLogging(__FUNCTION__, [], $document, $options); $result = parent::insertOne($document, $options); $this->logger->logQuery($event); return $result; }
/** * @param SavableModelInterface $model * @return void */ public function persist(SavableModelInterface $model) { $this->collection->insertOne($model->toArray()); $model->markAsStored(); }
/** * @param string $cbdSubject * @param MongoGraph $cbdGraph * @param Collection $collection * @param string $context * @throws \Exception */ protected function saveCBD($cbdSubject, MongoGraph $cbdGraph, Collection $collection, $context) { $cbdSubject = $this->labeller->uri_to_alias($cbdSubject); if ($cbdGraph == null || $cbdGraph->is_empty()) { throw new \Exception("graph for {$cbdSubject} was null"); } try { $collection->insertOne($cbdGraph->to_tripod_array($cbdSubject, $context), array("w" => 1)); print "."; } catch (\Exception $e) { if (preg_match('/E11000/', $e->getMessage())) { print "M"; // key already exists, merge it $criteria = array("_id" => array("r" => $cbdSubject, "c" => $context)); $existingGraph = new MongoGraph(); $existingGraph->add_tripod_array($collection->findOne($criteria)); $existingGraph->add_graph($cbdGraph); try { $collection->updateOne($criteria, ['$set' => $existingGraph->to_tripod_array($cbdSubject, $context)], array("w" => 1)); } catch (\Exception $e2) { throw new \Exception($e2->getMessage()); // todo: would be good to have typed exception } } else { // retry print "CursorException on update: " . $e->getMessage() . ", retrying\n"; try { $collection->insertOne($cbdGraph->to_tripod_array($cbdSubject, $context), array("w" => 1)); } catch (\Exception $e2) { throw new \Exception($e2->getMessage()); // todo: would be good to have typed exception } } } }