/**
  * @param string $identity
  * @return EventDescriptor[]
  */
 public function find(string $identity) : array
 {
     $cursor = $this->collection->find([$this->identityField => $identity]);
     return array_map(function (BSONDocument $eventData) : EventDescriptor {
         return EventDescriptor::reconstructFromArray($eventData->getArrayCopy());
     }, $cursor->toArray());
 }
 /**
  * @param QueryInterface $query
  * @param ModelInterface $model
  * @return ModelListInterface
  * @throws NotSupportedFilterException
  */
 public function find(QueryInterface $query, ModelInterface $model)
 {
     $queryArray = array();
     foreach ($query->getFilters() as $filter) {
         if (!in_array(get_class($filter), self::$supportedFilters)) {
             throw new NotSupportedFilterException(sprintf('%s filter is not supported or unknown.', get_class($filter)));
         }
         $queryArray[$filter->getFieldName()] = $filter->getValue();
     }
     $options = array();
     if ($query->getLimit() !== null) {
         $options['limit'] = $query->getLimit();
     }
     if ($query->getOffset() !== null) {
         $options['skip'] = $query->getOffset();
     }
     $list = new ModelList();
     $cursor = $this->collection->find($queryArray, $options);
     /** @var \MongoDB\Model\BSONDocument $doc */
     foreach ($cursor as $doc) {
         $docArray = (array) $doc;
         unset($docArray['_id']);
         /** @var ModelInterface $item */
         $item = new $model();
         $item->loadData($docArray);
         if ($item instanceof SavableModelInterface) {
             $item->markAsStored();
         }
         $list->addListItem($item);
     }
     return $list;
 }
Exemple #3
0
 /**
  * @param string $sagaType
  * @param array $associationValue
  * @return string[]
  */
 public function find(string $sagaType, array $associationValue) : array
 {
     $sagas = $this->collection->find(['type' => $sagaType, 'associations' => $associationValue]);
     return array_map(function (BSONDocument $sagaData) : string {
         $sagaDataArray = $sagaData->getArrayCopy();
         return $sagaDataArray['identity'];
     }, $sagas->toArray());
 }
Exemple #4
0
 public function getItems($offset, $itemCountPerPage)
 {
     $cursor = $this->collection->find([], ['skip' => $offset, 'limit' => $itemCountPerPage]);
     $items = [];
     foreach ($cursor as $item) {
         $items[] = $this->convertItemToArray($item);
     }
     return $items;
 }
Exemple #5
0
 public function find($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.find');
     }
     $res = $this->collection->find($filter, $options);
     if ($this->client->enableProfiling) {
         Yii::endProfile($token, 'mongoyii\\Collection.find');
     }
     return $res;
 }
 public function readList($model, $query, $fields = array(), $sortFields = array(), $limit = 0, $skip = 0)
 {
     $projection = array();
     foreach ($fields as $field) {
         $projection[$field] = true;
     }
     $options = array('projection' => $projection);
     if (count($sortFields) > 0) {
         $options['sort'] = $sortFields;
     }
     if ($limit > 0) {
         $options['limit'] = $limit;
     }
     if ($skip > 0) {
         $options['skip'] = $skip;
     }
     $cursor = $this->_collection->find($query, $options);
     $model->totalCount = $this->_collection->count($query);
     $model->entries = array();
     $ctr = 0;
     foreach ($cursor as $item) {
         $id = strval($item['_id']);
         $item[$this->_idKey] = $id;
         unset($item['_id']);
         $model->entries[] = $item;
         $ctr++;
     }
     $model->count = $ctr;
 }
Exemple #7
0
 /**
  * {@inheritdoc}
  */
 public function find($filter = [], array $options = [])
 {
     $event = $this->startQueryLogging(__FUNCTION__, $filter, null, $options);
     $result = parent::find($filter, $options);
     $this->logger->logQuery($event);
     return $result;
 }
Exemple #8
0
 /**
  * @param array $filter
  * @param array $options
  *
  * @return \Traversable
  */
 public function find(array $filter = [], array $options = [])
 {
     $cursor = $this->collection->find($filter, $options);
     $cursor->setTypeMap(['root' => 'array', 'document' => 'array', 'array' => 'array']);
     foreach ($cursor as $values) {
         (yield $this->hydrator->hydrate($values));
     }
 }
 /**
  * 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);
     }
 }
Exemple #10
0
 /**
  * @param array $criteria
  * @param int $offset
  * @param int $limit
  * @return Document[]
  */
 public function findBy(array $criteria, int $offset = 0, int $limit = 500) : array
 {
     $cursor = $this->collection->find($criteria, ['skip' => $offset, 'limit' => $limit]);
     return array_map(function (BSONDocument $document) : Document {
         $data = $document->getArrayCopy();
         unset($data['_id']);
         return $this->converter->arrayToObject($data, $this->documentClass);
     }, $cursor->toArray());
 }
 /**
  * @see DataModelInterface::listBooks
  */
 public function listBooks($limit = 10, $cursor = null)
 {
     if ($cursor) {
         $q = $this->db->find(array('_id' => array('$gt' => new ObjectId($cursor))), array('sort' => array('_id' => 1)));
     } else {
         $q = $this->db->find(array(), array('sort' => array('_id' => 1)));
     }
     $rows = array();
     $last_row = null;
     $new_cursor = null;
     foreach ($q as $row) {
         if (count($rows) == $limit) {
             $new_cursor = (string) $last_row->_id;
             break;
         }
         array_push($rows, $this->bookToArray($row));
         $last_row = $row;
     }
     return array('books' => $rows, 'cursor' => $new_cursor);
 }
 /**
  * {@inheritdoc}
  */
 public function keys()
 {
     try {
         $cursor = $this->collection->find(array(), array('projection' => array('_id' => 1)));
         $keys = array();
         foreach ($cursor as $document) {
             $keys[] = $document['_id'];
         }
     } catch (Exception $e) {
         throw ReadException::forException($e);
     }
     return $keys;
 }
Exemple #13
0
 /**
  * 
  * @return array
  */
 public function getDatasetRaces()
 {
     return $this->cacheGet('pie/races/', function () {
         $data = [Character::RACE_ASURA => ['y' => 0, 'name' => $this->trans('race.' . Character::RACE_ASURA)], Character::RACE_CHARR => ['y' => 0, 'name' => $this->trans('race.' . Character::RACE_CHARR)], Character::RACE_HUMAN => ['y' => 0, 'name' => $this->trans('race.' . Character::RACE_HUMAN)], Character::RACE_NORN => ['y' => 0, 'name' => $this->trans('race.' . Character::RACE_NORN)], Character::RACE_SYLVARI => ['y' => 0, 'name' => $this->trans('race.' . Character::RACE_SYLVARI)]];
         foreach ($this->collection->find() as $row) {
             if (isset($row['race'])) {
                 foreach ($row['race'] as $key => $value) {
                     $data[$key]['y'] += $value;
                 }
             }
         }
         return array_values($data);
     }, 4 * 3600);
 }
 public function testAggregateWithOut()
 {
     $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));
     if (!\MongoDB\server_supports_feature($server, self::$wireVersionForOutOperator)) {
         $this->markTestSkipped('$out aggregation pipeline operator is not supported');
     }
     $outputCollection = new Collection($this->manager, $this->getDatabaseName(), $this->getCollectionName() . '_output');
     $operation = new DropCollection($this->getDatabaseName(), $outputCollection->getCollectionName());
     $operation->execute($this->getPrimaryServer());
     $this->collection->aggregate([['$sort' => ['x' => 1]], ['$match' => ['_id' => ['$gt' => 1]]], ['$out' => $outputCollection->getCollectionName()]]);
     $expected = [['_id' => 2, 'x' => 22], ['_id' => 3, 'x' => 33]];
     $this->assertSameDocuments($expected, $outputCollection->find());
     // Manually clean up our output collection
     $operation = new DropCollection($this->getDatabaseName(), $outputCollection->getCollectionName());
     $operation->execute($this->getPrimaryServer());
 }
Exemple #15
0
 public function fetch(CriteriaManager $criteriaManager, Collection $collection) : array
 {
     $order = 1;
     $filter = [];
     $options = ['limit' => self::DEFAULT_LIMIT];
     $criteriaManager->doWith(SortCriteria::class, function (SortCriteria $criteria) use(&$options, &$order) {
         $order = strtolower($criteria->getOrder()) === 'asc' ? 1 : -1;
         $options['sort'] = [];
         $options['sort'][$criteria->getField()] = $order;
     });
     $criteriaManager->doWith(SeekCriteria::class, function (SeekCriteria $criteria) use(&$options, &$filter, $order) {
         $options['limit'] = $criteria->getLimit();
         $options['skip'] = 0;
         if ($criteria->getLastId()) {
             $lastId = new ObjectID($criteria->getLastId());
             if ($order === 1) {
                 $filter['_id'] = ['$gt' => $lastId];
             } else {
                 $filter['_id'] = ['$lt' => $lastId];
             }
         }
     });
     $criteriaManager->doWith(ThemeIdCriteria::class, function (ThemeIdCriteria $criteria) use(&$filter) {
         $filter[sprintf('theme_ids.%s', (string) $criteria->getThemeId())] = ['$exists' => true];
     });
     $criteriaManager->doWith(QueryStringCriteria::class, function (QueryStringCriteria $criteria) use(&$filter) {
         if ($criteria->isAvailable()) {
             $filter['$text'] = ['$search' => $criteria->getQuery()];
         }
     });
     $cursor = $collection->find($filter, $options)->toArray();
     if (count($cursor)) {
         $this->profileService->loadProfilesByIds(array_map(function (BSONDocument $document) {
             return (int) $document['id'];
         }, $cursor));
         return $this->cleanResults(array_map(function (BSONDocument $document) {
             try {
                 $profile = $this->profileService->getProfileById((int) $document['id']);
                 return array_merge(['_id' => (string) $document['_id']], $profile->toJSON());
             } catch (ProfileNotFoundException $e) {
                 return null;
             }
         }, $cursor));
     } else {
         return [];
     }
 }
 /**
  * Assert that the collections contain equivalent documents.
  *
  * This method will resolve references within the expected collection's
  * documents before comparing documents. Occurrences of "*result" in the
  * expected collection's documents will be replaced with the actual result.
  * Occurrences of "*actual" in the expected collection's documents will be
  * replaced with the corresponding value in the actual collection's document
  * being compared.
  *
  * @param Collection $expectedCollection
  * @param Collection $actualCollection
  * @param mixed      $actualResult
  */
 private function assertEquivalentCollections($expectedCollection, $actualCollection, $actualResult)
 {
     $mi = new MultipleIterator();
     $mi->attachIterator(new IteratorIterator($expectedCollection->find()));
     $mi->attachIterator(new IteratorIterator($actualCollection->find()));
     foreach ($mi as $documents) {
         list($expectedDocument, $actualDocument) = $documents;
         array_walk($expectedDocument, function (&$value) use($actualResult) {
             if ($value === '*result') {
                 $value = $actualResult;
             }
         });
         array_walk($expectedDocument, function (&$value, $key) use($actualDocument) {
             if (!is_string($value)) {
                 return;
             }
             if (!strncmp($value, '*actual_', 8)) {
                 $value = $actualDocument[$key];
             }
         });
         $this->assertSameDocument($expectedDocument, $actualDocument);
     }
 }
Exemple #17
0
 /**
  * @return \MongoDB\Driver\Cursor
  */
 public function getCondensedList() : \MongoDB\Driver\Cursor
 {
     return $this->collection->find([], ['projection' => ['feed.publicId' => true, 'feed.title' => true, 'feed.link' => true, 'feed.lastModified' => true, 'url' => true]]);
 }
 public function find($filter = [], array $options = [], $fillModels = true)
 {
     return $this->getQueryResult(parent::find($filter, $options), $fillModels);
 }
 public function find(array $query = [])
 {
     return $this->collection->find($query);
 }
Exemple #20
0
 /**
  * @param array $filter
  * @param array $options
  *
  * @return Iterator
  */
 public function find(array $filter = [], array $options = [])
 {
     $cursor = $this->collection->find($filter, $options);
     $cursor->setTypeMap(['root' => 'array', 'document' => 'array', 'array' => 'array']);
     return new Iterator($cursor, $this->hydrator);
 }
Exemple #21
0
 /**
  * Execute the query as a fresh "select" statement.
  *
  * @param  array  $columns
  * @return array|static[]
  */
 public function getFresh($columns = [])
 {
     // If no columns have been specified for the select statement, we will set them
     // here to either the passed columns, or the standard default of retrieving
     // all of the columns on the table using the "wildcard" column character.
     if (is_null($this->columns)) {
         $this->columns = $columns;
     }
     // Drop all columns if * is present, MongoDB does not work this way.
     if (in_array('*', $this->columns)) {
         $this->columns = [];
     }
     // Compile wheres
     $wheres = $this->compileWheres();
     // Use MongoDB's aggregation framework when using grouping or aggregation functions.
     if ($this->groups or $this->aggregate or $this->paginating) {
         $group = [];
         // Add grouping columns to the $group part of the aggregation pipeline.
         if ($this->groups) {
             foreach ($this->groups as $column) {
                 $group['_id'][$column] = '$' . $column;
                 // When grouping, also add the $last operator to each grouped field,
                 // this mimics MySQL's behaviour a bit.
                 $group[$column] = ['$last' => '$' . $column];
             }
             // Do the same for other columns that are selected.
             foreach ($this->columns as $column) {
                 $key = str_replace('.', '_', $column);
                 $group[$key] = ['$last' => '$' . $column];
             }
         }
         // Add aggregation functions to the $group part of the aggregation pipeline,
         // these may override previous aggregations.
         if ($this->aggregate) {
             $function = $this->aggregate['function'];
             foreach ($this->aggregate['columns'] as $column) {
                 // Translate count into sum.
                 if ($function == 'count') {
                     $group['aggregate'] = ['$sum' => 1];
                 } else {
                     $group['aggregate'] = ['$' . $function => '$' . $column];
                 }
             }
         }
         // When using pagination, we limit the number of returned columns
         // by adding a projection.
         if ($this->paginating) {
             foreach ($this->columns as $column) {
                 $this->projections[$column] = 1;
             }
         }
         // The _id field is mandatory when using grouping.
         if ($group and empty($group['_id'])) {
             $group['_id'] = null;
         }
         // Build the aggregation pipeline.
         $pipeline = [];
         if ($wheres) {
             $pipeline[] = ['$match' => $wheres];
         }
         if ($group) {
             $pipeline[] = ['$group' => $group];
         }
         // Apply order and limit
         if ($this->orders) {
             $pipeline[] = ['$sort' => $this->orders];
         }
         if ($this->offset) {
             $pipeline[] = ['$skip' => $this->offset];
         }
         if ($this->limit) {
             $pipeline[] = ['$limit' => $this->limit];
         }
         if ($this->projections) {
             $pipeline[] = ['$project' => $this->projections];
         }
         // Execute aggregation
         return $this->collection->aggregate($pipeline)->toArray();
     } elseif ($this->distinct) {
         // Return distinct results directly
         $column = isset($this->columns[0]) ? $this->columns[0] : '_id';
         // Execute distinct
         if ($wheres) {
             $result = $this->collection->distinct($column, $wheres);
         } else {
             $result = $this->collection->distinct($column);
         }
         return $result;
     } else {
         $columns = [];
         // Convert select columns to simple projections.
         foreach ($this->columns as $column) {
             $columns[$column] = true;
         }
         // Add custom projections.
         if ($this->projections) {
             $columns = array_merge($columns, $this->projections);
         }
         $options = [];
         if ($columns) {
             $options = ['projection' => $columns];
         }
         // Apply order, offset, limit and hint
         if ($this->orders) {
             $options['sort'] = $this->orders;
         }
         if ($this->offset) {
             $options['skip'] = $this->offset;
         }
         if ($this->limit) {
             $options['limit'] = $this->limit;
         }
         // Execute query and get
         $cursor = $this->collection->find($wheres, $options);
         // Return results as an array with numeric keys
         return iterator_to_array($cursor, false);
     }
 }