find() public method

Querys this collection
public find ( array $query = [], array $fields = [] ) : MongoCursor
$query array The fields for which to search.
$fields array Fields of the results to return.
return MongoCursor
Esempio n. 1
0
 /**
  * @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();
     }
     $list = new ModelList();
     $cursor = $this->collection->find($queryArray);
     if ($query->getLimit() !== null) {
         $cursor->limit($query->getLimit());
     }
     if ($query->getOffset() !== null) {
         $cursor->skip($query->getOffset());
     }
     foreach ($cursor as $doc) {
         unset($doc['_id']);
         /** @var ModelInterface $item */
         $item = new $model();
         $item->loadData($doc);
         if ($item instanceof SavableModelInterface) {
             $item->markAsStored();
         }
         $list->addListItem($item);
     }
     return $list;
 }
Esempio n. 2
0
 public function select($collectionName, $limit, $skip, $sort)
 {
     #gelen $tableName isimli collectiona bağlantı gerçekleştirelim.
     $Collection = new MongoCollection($this->mongodb, $collectionName);
     //controllerdan limit diye birşey gelmiyorsa
     if ($limit != '') {
         $limit = $limit;
     } else {
         $limit = 0;
     }
     //skip yani limit 5 den 10 a gibi
     if ($skip != '') {
         $skip = $skip;
     } else {
         $skip = 0;
     }
     //controllerdan sort diye bir sıralama geliyorsa
     if ($sort != '') {
         try {
             $selectResult = $Collection->find()->skip($skip)->limit($limit)->sort($sort);
         } catch (MongoCursorException $e) {
             die('select yaparken teknik bir sorunla karşılaşıldı ' . $e->getMessage());
         }
     } else {
         try {
             $selectResult = $Collection->find()->skip($skip)->limit($limit);
         } catch (MongoCursorException $e) {
             die('Select yaparken teknik bir sorunla karşılaşıldı ' . $e->getMessage());
         }
     }
     return $selectResult;
 }
Esempio n. 3
0
 public function find($criteria = [], $start = 0, $count = 20, $sortBy = null)
 {
     $cursor = $this->collection->find($criteria);
     if (is_numeric($start)) {
         $cursor->skip($start);
     }
     if (is_numeric($count)) {
         $cursor->limit($count);
     }
     if (is_array($sortBy)) {
         $cursor->sort($sortBy);
     }
     if ($cursor == null || $cursor->count(true) == 0) {
         return null;
     }
     if ($count == 1) {
         return new $this->entityClass($cursor->getNext());
     } else {
         $entities = [];
         foreach ($cursor as $r) {
             $entities[] = new $this->entityClass($r);
         }
         return $entities;
     }
 }
 /**
  * Initialize a QueryBuilder of latest log entries.
  *
  * @param $page
  * @param $logsPerPage
  * @param array $search
  * @return array
  */
 private function getLogsQueryBuilder($page, $logsPerPage, $search = array())
 {
     $skip = $logsPerPage * ($page - 1);
     $cursor = $this->collection->find($search);
     $cursor->skip($skip)->limit($logsPerPage)->sort(array('_id' => -1));
     return array('total' => $cursor->count(), 'results' => array_map([$this, 'convertArrayToEntity'], iterator_to_array($cursor)), 'search' => $search);
 }
Esempio n. 5
0
 /**
  * Zwraca liczbę elementów
  *
  * @return	int
  */
 public function count()
 {
     if ($this->iCount === null) {
         $this->iCount = $this->oColl->find($this->aQuery, $this->aFields)->count(true);
     }
     return $this->iCount;
 }
Esempio n. 6
0
 public function deleteExceedingQuota($quota)
 {
     $threshold = 0.9 * $quota;
     $currentSize = $this->getPictureTotalSize();
     $counter = 0;
     if ($currentSize > $threshold) {
         $toPurge = $currentSize - $threshold;
         // cleaning
         $cursor = $this->collection->find(['-class' => 'picture'], ['storageKey' => true, 'size' => true])->sort(['_id' => 1]);
         // starting from older pictures
         $sum = 0;
         foreach ($cursor as $item) {
             if ($sum < $toPurge) {
                 $this->storage->remove($item['storageKey']);
                 $this->collection->remove(['_id' => $item['_id']]);
                 $sum += $item['size'];
                 $counter++;
             } else {
                 // when we have deleted enough old pictures to reach the exceeding size to purge
                 break;
             }
         }
     }
     return $counter;
 }
 /**
  * MapReduce Result Set
  * @return MongoCursor
  */
 public function getResultSet(array $query = array())
 {
     if (!isset($this->collection)) {
         $this->collection = new MongoCollection($this->mongoDB, $this->_response["result"]);
     }
     return $this->collection->find($query);
 }
Esempio n. 8
0
 /**
  * {@inheritdoc}
  */
 public function loadTag($tag)
 {
     $cache = $this->collection->find(array('tags' => $this->mapTag($tag)), array('key'));
     $keys = array_map(function ($v) {
         return $v['key'];
     }, array_values(iterator_to_array($cache)));
     return empty($keys) ? null : $keys;
 }
 /**
  * @param AccountId $accountId
  * @return ExpenseListInOverview[]
  */
 public function getForAccount(AccountId $accountId)
 {
     $expenseLists = [];
     foreach ($this->collection->find(['accountId' => (string) $accountId]) as $expenseList) {
         $expenseLists[] = ExpenseListInOverview::deserialize($expenseList);
     }
     return $expenseLists;
 }
Esempio n. 10
0
 public function findAll()
 {
     $all = $this->contactsManagerCollection->find();
     $contacts = array();
     foreach ($all as $item) {
         $contacts[] = $this->createContact($item);
     }
     return $contacts;
 }
Esempio n. 11
0
 public function find($source)
 {
     $targets = $this->_collection->find(array('source' => $source), array('source' => false));
     $ret = array();
     foreach ($targets as $t) {
         $ret[] = (string) $t['_id'];
     }
     return $ret;
 }
Esempio n. 12
0
 /** Получение всех статей
  * @return array Result or null
  */
 public function get_all()
 {
     $coursor = ArticlesCollection::$collection->find();
     if ($coursor->count() == 0) {
         return null;
     }
     foreach ($coursor as $document) {
         $articles[] = $document;
     }
     return $articles;
 }
 public function testWrite()
 {
     $id = "somekey";
     $value = "Foo";
     $this->assertEquals(null, $this->collection->findOne());
     $cache = SS_Cache::factory(self::$cache_name);
     /** @var ICacheFrontend$cache */
     $cache->save($value, $id);
     $this->assertEquals(1, $this->collection->find()->count());
     $this->assertEquals($value, $this->collection->find()->getNext()['content']);
 }
 public function testFields()
 {
     $this->object->insert(array("x" => array(1, 2, 3, 4, 5)));
     $results = $this->object->find(array(), array("x" => array('$slice' => 3)))->getNext();
     $r = $results['x'];
     $this->assertTrue(array_key_exists(0, $r));
     $this->assertTrue(array_key_exists(1, $r));
     $this->assertTrue(array_key_exists(2, $r));
     $this->assertFalse(array_key_exists(3, $r));
     $this->assertFalse(array_key_exists(4, $r));
 }
 /**
  * Get a Document from the DocumentStore
  * @param array $ids IDs of Documents to get
  * @return array Documents matching $ids
  */
 public function getDocuments($ids)
 {
     $results = [];
     $documents = $this->documents->find(['id' => ['$in' => $ids]]);
     foreach ($documents as $result) {
         $document = new Document($result['title'], $result['content']);
         $document->id = $result['id'];
         $document->tokens = $result['tokens'];
         $results[$document->id] = $document;
     }
     return $results;
 }
Esempio n. 16
0
 /**
  */
 public function get($scope_ob)
 {
     try {
         $res = $this->_db->find(array(self::SCOPE => $scope_ob->scope, self::UID => $this->_params['user']), array(self::NAME => 1, self::VALUE => 1));
     } catch (MongoException $e) {
         throw new Horde_Prefs_Exception($e);
     }
     foreach ($res as $val) {
         $scope_ob->set($val[self::NAME], $val[self::VALUE]->bin);
     }
     return $scope_ob;
 }
Esempio n. 17
0
 public function get_all_for_article($article_id)
 {
     $coursor = CommentsCollection::$collection->find(["article_id" => $article_id]);
     if ($coursor->count() == 0) {
         return null;
     }
     foreach ($coursor as $document) {
         $document["saved_at"] = date('Y-m-d H:i', $document["saved_at"]->sec);
         $comments[] = $document;
     }
     return $comments;
 }
Esempio n. 18
0
 /**
  * @test
  */
 public function initialize()
 {
     $this->collection->drop();
     $author = new Author('kirk');
     $user = new Netizen($author);
     $user->setProfile(new \Trismegiste\SocialBundle\Security\Profile());
     $this->repository->persist($user);
     $source = new SmallTalk($author);
     $this->repository->batchPersist([$source, $source, $source]);
     $this->assertCount(4, $this->collection->find());
     return (string) $user->getId();
 }
 public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 {
     $cursor = $this->mongoCollection->find($criteria);
     if ($orderBy !== null) {
         $cursor->sort($orderBy);
     }
     if ($limit !== null) {
         $cursor->limit($limit);
     }
     if ($offset !== null) {
         $cursor->skip($offset);
     }
     return iterator_to_array($cursor);
 }
Esempio n. 20
0
 /**
  * Retrieves several items from the cache store in a single transaction.
  *
  * If not all of the items are available in the cache then the data value for those that are missing will be set to false.
  *
  * @param array $keys The array of keys to retrieve
  * @return array An array of items from the cache.
  */
 public function get_many($keys)
 {
     if ($this->extendedmode) {
         $query = $this->get_many_extendedmode_query($keys);
         $keyarray = array();
         foreach ($keys as $key) {
             $keyarray[] = $key['key'];
         }
         $keys = $keyarray;
         $query = array('key' => array('$in' => $keys));
     } else {
         $query = array('key' => array('$in' => $keys));
     }
     $cursor = $this->collection->find($query);
     $results = array();
     foreach ($cursor as $result) {
         $id = (string) $result['key'];
         $results[$id] = unserialize($result['data']);
     }
     foreach ($keys as $key) {
         if (!array_key_exists($key, $results)) {
             $results[$key] = false;
         }
     }
     return $results;
 }
 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());
 }
Esempio n. 22
0
 /**
  * Finds documents by a set of criteria.
  *
  * @param array        $criteria Query criteria
  * @param array        $sort     Sort array for Cursor::sort()
  * @param integer|null $limit    Limit for Cursor::limit()
  * @param integer|null $skip     Skip for Cursor::skip()
  * @return Cursor
  */
 public function loadAll(array $criteria = array(), array $sort = null, $limit = null, $skip = null)
 {
     $criteria = $this->prepareQueryOrNewObj($criteria);
     $criteria = $this->addDiscriminatorToPreparedQuery($criteria);
     $criteria = $this->addFilterToPreparedQuery($criteria);
     $baseCursor = $this->collection->find($criteria);
     $cursor = $this->wrapCursor($baseCursor);
     /* The wrapped cursor may be used if the ODM cursor becomes wrapped with
      * an EagerCursor, so we should apply the same sort, limit, and skip
      * options to both cursors.
      */
     if (null !== $sort) {
         $baseCursor->sort($this->prepareSortOrProjection($sort));
         $cursor->sort($sort);
     }
     if (null !== $limit) {
         $baseCursor->limit($limit);
         $cursor->limit($limit);
     }
     if (null !== $skip) {
         $baseCursor->skip($skip);
         $cursor->skip($skip);
     }
     return $cursor;
 }
Esempio n. 23
0
 /**
  * authenticate() - defined by Zend_Auth_Adapter_Interface.  This method is called to
  * attempt an authentication.  Previous to this call, this adapter would have already
  * been configured with all necessary information to successfully connect to a database
  * collection and attempt to find a record matching the provided identity.
  *
  * @throws Zend_Auth_Adapter_Exception if answering the authentication query is impossible
  * @return Zend_Auth_Result
  */
 public function authenticate()
 {
     $this->_authenticateSetup();
     $cursor = $this->_collection->find(array($this->_identityKeyPath => $this->_identity));
     $count = $cursor->count();
     if ($count == 0) {
         $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
         $this->_authenticateResultInfo['messages'][] = 'A record with the supplied identity could not be found.';
     } elseif ($count == 1) {
         $resultIdentity = $cursor->getNext();
         $this->_resultDoc = $resultIdentity;
         if (password_verify($this->_credential, $resultIdentity[$this->_credentialKeyPath])) {
             $this->_authenticateResultInfo['code'] = Zend_Auth_Result::SUCCESS;
             $this->_authenticateResultInfo['messages'][] = 'Authentication successful.';
         } else {
             $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
             $this->_authenticateResultInfo['messages'][] = 'Supplied credential is invalid.';
         }
     } elseif ($count > 1) {
         $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS;
         $this->_authenticateResultInfo['messages'][] = 'More than one record matches the supplied identity.';
     }
     $authResult = $this->_authenticateCreateAuthResult();
     return $authResult;
 }
Esempio n. 24
0
 /**
  * @unused?
  * generalized mongo query
  * @param array $query
  * @param MongoCollection $collection
  * @return array
  * @throws modelException
  */
 protected function findByArray($query = [], \MongoCollection $collection)
 {
     if (count($query) < 1) {
         throw new modelException('array is required');
     }
     return iterator_to_array($collection->find($query));
 }
Esempio n. 25
0
 public function getScholarPost()
 {
     $col = new MongoCollection($this->con, COL_ARTICLES);
     $scholar = array("tag" => "scholar", "archieve" => "0");
     $cur = $col->find($scholar);
     return $cur;
 }
 /**
  * Link files to the Mongo product values.
  *
  * @param string $productValueTable
  */
 public function migrateMediasOnProductValue($productValueTable)
 {
     $db = $this->getMongoDatabase();
     $valueCollection = new \MongoCollection($db, $productValueTable);
     $productsWithMedia = $valueCollection->find(['values.media' => ['$ne' => null]]);
     $stmt = $this->ormConnection->prepare('SELECT fi.id FROM akeneo_file_storage_file_info fi WHERE fi.old_file_key = ?');
     foreach ($productsWithMedia as $product) {
         foreach ($product['values'] as $index => $value) {
             if (isset($value['media']) && isset($value['media']['filename'])) {
                 $stmt->bindValue(1, $value['media']['filename']);
                 $stmt->execute();
                 $fileInfo = $stmt->fetch();
                 /*
                 db.pim_catalog_product.update(
                    {
                        _id: ObjectId("55ee950c48177e12588b5ccb"),
                        "values._id": ObjectId("55ee950c48177e12588b5cd4")
                    },
                    { $set: {"values.$.media": NumberLong(666)} }
                 )
                 */
                 if ((int) $fileInfo['id'] > 0) {
                     $valueCollection->update(['_id' => new \MongoId($product['_id']), 'values._id' => new \MongoId($value['_id'])], ['$set' => ['values.$.media' => (int) $fileInfo['id']]]);
                 }
             }
         }
     }
 }
Esempio n. 27
0
 /**
  * Added by me
  * 
  * Finds messages matching the query and removes from queue
  * @param array $query in same format as \MongoCollection::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 bool $logging whether logging is enabled or not 
  * @param array $logdata optional log data to be stored in _processed collection
  * @return void
  *
  * @throws \InvalidArgumentException key in $query was not a string
  */
 public function delqueues(array $query, $logging = false, $logdata = array())
 {
     if (!is_bool($logging)) {
         throw new \InvalidArgumentException('$logging was not a bool');
     }
     $removeQuery = array();
     foreach ($query as $key => $value) {
         if (!is_string($key)) {
             throw new \InvalidArgumentException('key in $query was not a string');
         }
         $removeQuery["payload.{$key}"] = $value;
     }
     if (count($removeQuery) > 0) {
         if ($logging && $this->_collection_processed != null) {
             $cursor = $this->_collection->find($removeQuery);
             foreach ($cursor as $doc) {
                 if ($doc !== null && array_key_exists('_id', $doc)) {
                     $deleted_message = array('payload' => $doc['payload'], 'log' => $logdata, 'pts' => new \MongoDate(), 'qd' => true);
                     $this->_collection_processed->insert($deleted_message);
                 }
             }
         }
         // remove queues
         $this->_collection->remove($removeQuery);
     }
 }
Esempio n. 28
0
function dataBaseCall($collectionName)
{
    $m = new MongoClient();
    $db = $m->selectDB('SocialMedia');
    $collection = new MongoCollection($db, $collectionName);
    $cursor = $collection->find();
    return $cursor;
}
Esempio n. 29
0
 /**
  * @test
  */
 public function initialize()
 {
     $this->collection->drop();
     $author = [];
     foreach (['kirk', 'spock', 'mccoy'] as $nick) {
         $author[] = new Author($nick);
     }
     $source = new SmallTalk($author[0]);
     $this->repository->persist($source);
     $rep[0] = new Repeat($author[1]);
     $rep[0]->setEmbedded($source);
     $this->repository->persist($rep[0]);
     $rep[1] = new Repeat($author[2]);
     $rep[1]->setEmbedded($rep[0]);
     $this->repository->persist($rep[1]);
     $this->assertCount(3, $this->collection->find());
 }
Esempio n. 30
0
/**
 * Lists everything in the specified collection
 * 
 * @param MongoCollection $collection
 */
function dumpCollection(MongoCollection $collection, $query = [])
{
    // Find things in this collection matching the supplied query
    $cursor = $collection->find($query);
    foreach ($cursor as $document) {
        echo "\t{$document['name']}\n";
        dumpRecursive($collection->db, $document);
    }
}