/** * @param string $id * @return BSONDocument */ public function find(string $id) : BSONDocument { $feedObject = $this->collection->findOne(['_id' => new ObjectID($id)]); if (!$feedObject instanceof BSONDocument) { throw new \RuntimeException("feed {$id} not found"); } return $feedObject; }
/** * @param string $identity * @return string */ public function findById(string $identity) : string { $sagaData = $this->collection->findOne(['identity' => $identity]); if (empty($sagaData)) { return ''; } return $sagaData['serialized']; }
/** * @param string $identity * @return Document * @throws DocumentNotFoundException */ public function find(string $identity) : Document { /* @var $result BSONDocument */ $result = $this->collection->findOne([$this->identityField => $identity]); if ($result == null) { throw new DocumentNotFoundException($identity); } $data = $result->getArrayCopy(); unset($data['_id']); return $this->converter->arrayToObject($data, $this->documentClass); }
public function findOne($filter = [], $options = []) { $collectionName = $this->collection->getCollectionName(); $serialisedQuery = json_encode(['$query' => $filter, '$options' => $options]); Yii::trace("Executing find: {$serialisedQuery}", 'mongoyii\\Collection'); if ($this->client->enableProfiling) { $token = "mongoyii\\{$collectionName}.find({$serialisedQuery})"; Yii::beginProfile($token, 'mongoyii\\Collection.findOne'); } $res = $this->collection->findOne($filter, $options); if ($this->client->enableProfiling) { Yii::endProfile($token, 'mongoyii\\Collection.findOne'); } return $res; }
/** * @param array $filter * @param array $options * * @return object */ public function findOne(array $filter = [], array $options = []) { $options['typeMap'] = ['root' => 'array', 'document' => 'array', 'array' => 'array']; if ($values = $this->collection->findOne($filter, $options)) { return $this->hydrator->hydrate($values); } }
/** * {@inheritdoc} */ public function findOne($filter = [], array $options = []) { $event = $this->startQueryLogging(__FUNCTION__, $filter, null, $options); $result = parent::findOne($filter, $options); $this->logger->logQuery($event); return $result; }
/** * Retrieve the cached results of the api $request. * * @param RequestInterface $request A request for which the response may be cached. * * @return ResponseInterface|null */ public function get(RequestInterface $request) { $cached = $this->collection->findOne(['_id' => $request->getUrl()]); if ($cached === null) { return null; } $headers = $cached['headers']; if ($headers instanceof BSONArray) { $headers = $headers->getArrayCopy(); } $body = $cached['body']; if ($body instanceof BSONArray) { $body = $body->getArrayCopy(); } return new Response($cached['httpCode'], $headers, $body); }
/** * Get a non running message from the queue. * * @param array $query in same format as \MongoDB\Collection::find() where top level fields do not contain operators. * Lower level fields can however. eg: valid {a: {$gt: 1}, "b.c": 3}, * invalid {$and: [{...}, {...}]} * @param int $runningResetDuration second duration the message can stay unacked before it resets and can be * retreived again. * @param int $waitDurationInMillis millisecond duration to wait for a message. * @param int $pollDurationInMillis millisecond duration to wait between polls. * * @return array|null the message or null if one is not found * * @throws \InvalidArgumentException $runningResetDuration, $waitDurationInMillis or $pollDurationInMillis was not * an int * @throws \InvalidArgumentException key in $query was not a string */ public function get(array $query, $runningResetDuration, $waitDurationInMillis = 3000, $pollDurationInMillis = 200) { if (!is_int($runningResetDuration)) { throw new \InvalidArgumentException('$runningResetDuration was not an int'); } if (!is_int($waitDurationInMillis)) { throw new \InvalidArgumentException('$waitDurationInMillis was not an int'); } if (!is_int($pollDurationInMillis)) { throw new \InvalidArgumentException('$pollDurationInMillis was not an int'); } if ($pollDurationInMillis < 0) { $pollDurationInMillis = 0; } //reset stuck messages $this->collection->updateMany(['running' => true, 'resetTimestamp' => ['$lte' => new \MongoDB\BSON\UTCDateTime((int) (microtime(true) * 1000))]], ['$set' => ['running' => false]]); $completeQuery = ['running' => false]; foreach ($query as $key => $value) { if (!is_string($key)) { throw new \InvalidArgumentException('key in $query was not a string'); } $completeQuery["payload.{$key}"] = $value; } $completeQuery['earliestGet'] = ['$lte' => new \MongoDB\BSON\UTCDateTime((int) (microtime(true) * 1000))]; $resetTimestamp = time() + $runningResetDuration; //ints overflow to floats if (!is_int($resetTimestamp)) { $resetTimestamp = $runningResetDuration > 0 ? self::MONGO_INT32_MAX : 0; } $resetTimestamp = min(max(0, $resetTimestamp * 1000), self::MONGO_INT32_MAX); $update = ['$set' => ['resetTimestamp' => new \MongoDB\BSON\UTCDateTime($resetTimestamp), 'running' => true]]; $options = ['sort' => ['priority' => 1, 'created' => 1]]; //ints overflow to floats, should be fine $end = microtime(true) + $waitDurationInMillis / 1000.0; $sleepTime = $pollDurationInMillis * 1000; //ints overflow to floats and already checked $pollDurationInMillis was positive if (!is_int($sleepTime)) { //ignore since testing a giant sleep takes too long //@codeCoverageIgnoreStart $sleepTime = PHP_INT_MAX; } //@codeCoverageIgnoreEnd while (true) { $message = $this->collection->findOneAndUpdate($completeQuery, $update, $options); //checking if _id exist because findAndModify doesnt seem to return null when it can't match the query on //older mongo extension if ($message !== null && array_key_exists('_id', $message)) { // findOneAndUpdate does not correctly return result according to typeMap options so just refetch. $message = $this->collection->findOne(['_id' => $message->_id]); //id on left of union operator so a possible id in payload doesnt wipe it out the generated one return ['id' => $message['_id']] + (array) $message['payload']; } if (microtime(true) >= $end) { return null; } usleep($sleepTime); } //ignore since always return from the function from the while loop //@codeCoverageIgnoreStart }
/** * @see DataModelInterface::read */ public function read($id) { $result = $this->db->findOne(array('_id' => new ObjectId($id))); if ($result) { return $this->bookToArray($result); } return false; }
/** * Find ONe or several documents */ public function find($filter = [], array $options = [], $multiple = true) { if ($multiple === true) { return parent::find($filter, $options); } else { return parent::findOne($filter, $options); } }
/** * Querys this collection, returning a single element * @link http://www.php.net/manual/en/mongocollection.findone.php * @param array $query The fields for which to search. * @param array $fields Fields of the results to return. * @return array|null */ public function findOne(array $query = array(), array $fields = array()) { $document = $this->collection->findOne(TypeConverter::convertLegacyArrayToObject($query), ['projection' => $fields]); if ($document !== null) { $document = TypeConverter::convertObjectToLegacyArray($document); } return $document; }
/** * Querys this collection, returning a single element * * @link http://www.php.net/manual/en/mongocollection.findone.php * @param array $query The fields for which to search. * @param array $fields Fields of the results to return. * @param array $options * @return array|null */ public function findOne(array $query = [], array $fields = [], array $options = []) { $options = ['projection' => $fields] + $options; $document = $this->collection->findOne(TypeConverter::fromLegacy($query), $options); if ($document !== null) { $document = TypeConverter::toLegacy($document); } return $document; }
public function readSubDocument($model, $rootId, $property, $id) { CodeGuard::checkTypeAndThrow($rootId, 'string'); CodeGuard::checkTypeAndThrow($id, 'string'); $data = $this->_collection->findOne(array("_id" => self::mongoID($rootId)), array('projection' => $property . '.' . $id)); if ($data === NULL) { throw new \Exception("Could not find {$property}={$id} in {$rootId}"); } // TODO Check this out on nested sub docs > 1 $data = $data[$property][$id]; MongoDecoder::decode($model, $data, $id); }
/** * Querys this collection, returning a single element * * @link http://www.php.net/manual/en/mongocollection.findone.php * @param array $query The fields for which to search. * @param array $fields Fields of the results to return. * @param array $options * @return array|null */ public function findOne(array $query = [], array $fields = [], array $options = []) { $options = ['projection' => $fields] + $options; try { $document = $this->collection->findOne(TypeConverter::fromLegacy($query), $options); } catch (\MongoDB\Driver\Exception\Exception $e) { ExceptionConverter::toLegacy($e); } if ($document !== null) { $document = TypeConverter::toLegacy($document); } return $document; }
/** * {@inheritdoc} */ public function getOrFail($key) { KeyUtil::validate($key); try { $document = $this->collection->findOne(array('_id' => $key), array('typeMap' => self::$typeMap)); } catch (Exception $e) { throw ReadException::forException($e); } if (null === $document) { throw NoSuchKeyException::forKey($key); } return $this->unserialize->__invoke($document['value']); }
/** * Returns the array containing all cities in a country. * * @author Shivam Mathur <*****@*****.**> * * @param $countryName * @param bool $test * @return array * @throws \Exception */ private function cities($countryName, $test = false) { if ($countryName == '_id') { throw new \Exception('Could not found the country - ' . $countryName); } $locationData = []; if (!$test) { $locationData = $this->database->findOne([], ['projection' => ['_id' => false, $countryName => true], 'typeMap' => ['root' => 'array', 'document' => 'array']]); } if (!$locationData) { throw new \Exception('Could not found the country - ' . $countryName); } // Getting names of cities from $locationData $cities = $locationData[$countryName]; sort($cities); return $cities; }
/** * Querys this collection, returning a single element * * @link http://www.php.net/manual/en/mongocollection.findone.php * @param array $query The fields for which to search. * @param array $fields Fields of the results to return. * @param array $options * @return array|null */ public function findOne($query = [], array $fields = [], array $options = []) { // Can't typehint for array since MongoGridFS extends and accepts strings if (!is_array($query)) { trigger_error(sprintf('MongoCollection::findOne(): expects parameter 1 to be an array or object, %s given', gettype($query)), E_WARNING); return; } $options = ['projection' => TypeConverter::fromLegacy($fields)] + $options; try { $document = $this->collection->findOne(TypeConverter::fromLegacy($query), $options); } catch (\MongoDB\Driver\Exception\Exception $e) { throw ExceptionConverter::toLegacy($e); } if ($document !== null) { $document = TypeConverter::toLegacy($document); } return $document; }
/** * Read session data * * @param string $id * @return string */ public function read($id) { $session = $this->mongoCollection->findOne(['_id' => $id, $this->options->getNameField() => $this->sessionName]); if (null !== $session) { // check if session has expired if index is not used if (!$this->options->useExpireAfterSecondsIndex()) { $timestamp = $session[$this->options->getLifetimeField()]; $timestamp += floor((string) $session[$this->options->getModifiedField()] / 1000); // session expired if ($timestamp <= time()) { $this->destroy($id); return ''; } } return $session[$this->options->getDataField()]->getData(); } return ''; }
public function findById($id) { return $this->collection->findOne(['_id' => new ObjectID($id)]); }
/** * Add to process registry. Adds based on $maxGlobalProcesses and $maxHostProcesses after a process registry cleaning. * * @param \MongoDB\Collection $collection the collection * @param string $id a unique id * @param int $minsBeforeExpire number of minutes before a process is considered expired. * @param int $maxGlobalProcesses max processes of an id allowed to run across all hosts. * @param int $maxHostProcesses max processes of an id allowed to run across a single host. * * @return boolean true if the process was added, false if not or there is too much concurrency at the moment. * * @throws \InvalidArgumentException if $id was not a string * @throws \InvalidArgumentException if $minsBeforeExpire was not an int * @throws \InvalidArgumentException if $maxGlobalProcesses was not an int * @throws \InvalidArgumentException if $maxHostProcesses was not an int */ public static function add(\MongoDB\Collection $collection, $id, $minsBeforeExpire = PHP_INT_MAX, $maxGlobalProcesses = 1, $maxHostProcesses = 1) { if (!is_string($id)) { throw new \InvalidArgumentException('$id was not a string'); } if (!is_int($minsBeforeExpire)) { throw new \InvalidArgumentException('$minsBeforeExpire was not an int'); } if (!is_int($maxGlobalProcesses)) { throw new \InvalidArgumentException('$maxGlobalProcesses was not an int'); } if (!is_int($maxHostProcesses)) { throw new \InvalidArgumentException('$maxHostProcesses was not an int'); } $thisHostName = self::_getEncodedHostname(); $thisPid = getmypid(); //loop in case the update fails its optimistic concurrency check for ($i = 0; $i < 5; ++$i) { $collection->findOneAndUpdate(['_id' => $id], ['$setOnInsert' => ['hosts' => [], 'version' => new \MongoDB\BSON\ObjectID()]], ['upsert' => true]); $existing = $collection->findOne(['_id' => $id], ['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']]); $replacement = $existing; $replacement['version'] = new \MongoDB\BSON\ObjectID(); //clean $replacement based on their pids and expire times foreach ($existing['hosts'] as $hostname => $pids) { foreach ($pids as $pid => $expires) { //our machine and not running //the task expired //our machine and pid is recycled (should rarely happen) if ($hostname === $thisHostName && !file_exists("/proc/{$pid}") || time() >= $expires->toDateTime()->getTimestamp() || $hostname === $thisHostName && $pid === $thisPid) { unset($replacement['hosts'][$hostname][$pid]); } } if (empty($replacement['hosts'][$hostname])) { unset($replacement['hosts'][$hostname]); } } $totalPidCount = 0; foreach ($replacement['hosts'] as $hostname => $pids) { $totalPidCount += count($pids); } $thisHostPids = array_key_exists($thisHostName, $replacement['hosts']) ? $replacement['hosts'][$thisHostName] : []; if ($totalPidCount >= $maxGlobalProcesses || count($thisHostPids) >= $maxHostProcesses) { return false; } // add our process $expireSecs = time() + $minsBeforeExpire * 60; if (!is_int($expireSecs)) { if ($minsBeforeExpire > 0) { $expireSecs = self::MONGO_INT32_MAX; } else { $expireSecs = 0; } } $thisHostPids[$thisPid] = new \MongoDB\BSON\UTCDateTime($expireSecs * 1000); $replacement['hosts'][$thisHostName] = $thisHostPids; $status = $collection->replaceOne(['_id' => $existing['_id'], 'version' => $existing['version']], $replacement, ['writeConcern' => new \MongoDB\Driver\WriteConcern(1, 100, true)]); if ($status->getMatchedCount() === 1) { return true; } //@codeCoverageIgnoreStart //hard to test the optimistic concurrency check } //too much concurrency at the moment, return false to signify not added. return false; //@codeCoverageIgnoreEnd }
/** * {@inheritdoc} */ public function getData($key) { $doc = $this->collection->findOne(['_id' => self::mapKey($key)]); return $doc ? ['data' => unserialize($doc['data']), 'expiration' => $doc['expiration']] : false; }
/** * @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 } } } }
/** * * @param MongoCollection $collection */ public function calculateStatistics(MongoCollection $collection, $quiet = true) { try { $data = $collection->findOne(['account' => $this->getName()]); if (!empty($data) && time() - $data['last_update'] < 86400) { return; } $data = ['account' => $this->getName(), 'last_update' => time(), 'wallet' => $this->getStatsWallet(), 'unlocks' => $this->getStatsUnlocks(), 'pvp' => $this->getStatsPvp(), 'race' => $this->getRaceCount(), 'gender' => $this->getGenderCount(), 'profession' => $this->getProfessionCount(), 'generic' => ['characters' => $this->getCharactersCount(), 'age' => $this->getTotalAge(), 'deaths' => $this->getTotalDeaths(), 'level80' => $this->getCharactersLevel80Count()], Item::RARITY_ASCENDED => $this->getAscendedCount(), Item::RARITY_LEGENDARY => $this->getLegendariesCount()]; $collection->updateOne(['account' => $this->getName()], $data, ['upsert' => true]); } catch (\Exception $ex) { if (!$quiet) { throw $ex; } } }