{@inheritdoc}

This method must be improved in future versions!

@see https://github.com/mongodb/mongo-php-library/issues/317
@see https://github.com/slimphp/Slim/issues/2112
@see https://jira.mongodb.org/browse/PHPLIB-213
430631
public function getStream(BucketInterface $bucket, string $name): StreamInterface
    {
        $file = $this->gridFS($bucket)->findOne(['filename' => $name]);
        if (empty($file)) {
            throw new ServerException(
                "Unable to create stream for '{$name}', object does not exists"
            );
        }

        //We have to use temporary file now due to issues with seeking (should be fixed soon)
        $resource = fopen('php://memory', 'rw');

        //Copying from non seekable to seekable stream
        stream_copy_to_stream($this->gridFS($bucket)->openDownloadStream($file->_id), $resource);

        //Working thought the memory, WILL FAIL on very huge files
        rewind($resource);

        //Ugly :/
        return stream_for($resource);
    }
1180754
public function showCollections()
    {
        // Get dependencies
        $collectionMapper = ($this->container->dataMapper)('CollectionMapper');
        $pageMapper = ($this->container->dataMapper)('PageMapper');

        // Fetch collection pages, and chuck pages into sub-array by collection ID with meta info
        $collectionPages = $pageMapper->findCollectionPages();
        foreach ($collectionPages as $col) {
            if (!isset($data['collectionPages'][$col->collection_id])) {
                $data['collectionPages'][$col->collection_id]['collection_id'] = $col->collection_id;
                $data['collectionPages'][$col->collection_id]['collection_title'] = $col->collection_title;
                $data['collectionPages'][$col->collection_id]['collection_slug'] = $col->collection_slug;
            }

            $data['collectionPages'][$col->collection_id]['pages'][] = $col;
        }

        // Get available templates and collection groups
        $data['templates'] = $this->getPageTemplates('collection');
        $data['collections'] = $collectionMapper->find();

        // Enrich collections array with matching description from templates array
        $templateArray = array_column($data['templates'], 'filename');
        array_walk($data['collections'], function (&$collect) use ($data, $templateArray) {
            // Find matching collection template key for reference in $templateArray
            $key = array_search($collect->definition, $templateArray);
            $collect->templateName = $data['templates'][$key]['name'];
            $collect->templateDescription = $data['templates'][$key]['description'];
        });

        return $this->render('collections.html', $data);
    }
510300
public function getFiltered($page, $numRows, $sortAttr, $sortOrder, $searchAttr, $searchValue, $richFilters = [])
    {
        $query = $this->prepareQuery();

        $query = $this->richFiltersOnQuery($query, $richFilters);

        if ($sortAttr && $sortOrder && $this->inScope($sortAttr)) {
            $scope = $this->getScope($sortAttr);
            $query = $query->orderBy($scope, $sortOrder);
        }

        if ($searchAttr && $searchValue && $this->inScope($searchAttr)) {
            $scope = $this->getScope($searchAttr);
            $query = $query->where($scope, 'like', '%' . $searchValue . '%');
        }

        $collection = $query->get();

        $collection = $this->addPermissions($collection);

        $collection = $this->formatCollection($collection);

        $collection = $collection->each(function ($model) {
            $model = $this->formatModel($model);
        });

        if ($sortAttr && $sortOrder && ! $this->inScope($sortAttr)) {
            $collection = $sortOrder == 'asc'
                ? $collection->sortBy($sortAttr)
                : $collection->sortByDesc($sortAttr);
        }

        $collection = $this->richFiltersOnCollection($collection, $richFilters);

        if ($searchAttr && $searchValue && ! $this->inScope($searchAttr)) {
            $collection = $collection->filter(function ($model) use ($searchAttr, $searchValue) {
                $value = (string) $model->$searchAttr;
                $value = strtolower($value);
                $search = strtolower($searchValue);
                return strpos($value, $search) !== false;
            });
        }

        if ($page && $numRows) {
            $toSkip = ($page - 1) * $numRows;
            $count = $collection->count();
            $collection = $collection->take(- ($count - $toSkip))->take($numRows);
        } else if ($numRows)
            $collection = $collection->take($numRows);

        return collect(array_values($collection->toArray()));
    }
981780
public function getBytes()
    {
        if ($this->isDirty && $this->bytes) {
            return $this->bytes;
        }
        if ($this->isDirty && $this->filename) {
            return file_get_contents($this->filename);
        }
        if ($this->mongoGridFSFile instanceof \MongoGridFSFile) {
            return $this->mongoGridFSFile->getBytes();
        }
        return null;
    }
62273
public function each($collection=null, $iterator=null) {
    list($collection, $iterator) = self::_wrapArgs(func_get_args(), 2);
    
    if(is_null($collection)) return self::_wrap(null);
    
    $collection = (array) self::_collection($collection);
    if(count($collection) === 0) return self::_wrap(null);
    
    foreach($collection as $k=>$v) {
      call_user_func($iterator, $v, $k, $collection);
    }
    return self::_wrap(null);
  }
1309330
public function initMapper() {
		switch ($this->dbsType) {
			case 'jig':
				$this->mapper = new Jig\Mapper($this->db, $this->table);
				break;
			case 'sql':
				// ensure to load full table schema, so we can work with it at runtime
				$this->mapper = new SQL\Mapper($this->db, $this->table, null,
					($this->fluid)?0:$this->ttl);
				$this->applyWhitelist();
				break;
			case 'mongo':
				$this->mapper = new Mongo\Mapper($this->db, $this->table);
				break;
			default:
				trigger_error(sprintf(self::E_UNKNOWN_DB_ENGINE,$this->dbsType),E_USER_ERROR);
		}
		$this->queryParser = CortexQueryParser::instance();
		$this->reset();
		$this->clearFilter();
		$f3 = \Base::instance();
		$this->smartLoading = $f3->exists('CORTEX.smartLoading') ?
			$f3->get('CORTEX.smartLoading') : TRUE;
		$this->standardiseID = $f3->exists('CORTEX.standardiseID') ?
			$f3->get('CORTEX.standardiseID') : TRUE;
		if(!empty($this->fieldConf))
			foreach($this->fieldConf as &$conf) {
				$conf=static::resolveRelationConf($conf,$this->primary);
				unset($conf);
			}
	}
752666
function removeThis( $id, $currentVersion = null )
    {
        $dataType = $this->dataType();
        if ( !$dataType )
            return false;
        $dataType->deleteStoredObjectAttribute( $this, $currentVersion );
        if( $currentVersion == null )
        {
            eZPersistentObject::removeObject( eZContentObjectAttribute::definition(),
                                              array( "id" => $id ) );
        }
        else
        {
            eZPersistentObject::removeObject( eZContentObjectAttribute::definition(),
                                              array( "id" => $id,
                                                     "version" => $currentVersion ) );
        }
    }
1215924
private function addMongoNode()
    {
        $builder = new TreeBuilder('mongodb');
        $node    = $this->getRootNode($builder, 'mongodb');

        $node
            ->addDefaultsIfNotSet()
            ->children()
                ->scalarNode('connection_id')->defaultNull()->end()
                ->scalarNode('collection_id')->defaultNull()->end()
                ->scalarNode('database_name')->defaultValue('doctrine_cache')->end()
                ->scalarNode('collection_name')->defaultValue('doctrine_cache')->end()
                ->scalarNode('server')->defaultValue('%doctrine_cache.mongodb.server%')->end()
            ->end()
        ;

        return $node;
    }
416795
protected function _init() {
		$hosts = [];
		foreach ((array) $this->_config['host'] as $host) {
			$host = HostString::parse($host) + [
				'host' => static::DEFAULT_HOST,
				'port' => static::DEFAULT_PORT
			];
			$hosts[] = "{$host['host']}:{$host['port']}";
		}
		if ($this->_config['login']) {
			$this->_config['dsn'] = sprintf(
				'mongodb://%s:%s@%s/%s',
				$this->_config['login'],
				$this->_config['password'],
				implode(',', $hosts),
				$this->_config['database']
			);
		} else {
			$this->_config['dsn'] = sprintf(
				'mongodb://%s',
				implode(',', $hosts)
			);
		}
		parent::_init();

		$this->_operators += [
			'like' => function($key, $value) {
				return new MongoRegex($value);
			},
			'$exists' => function($key, $value) {
				return ['$exists' => (boolean) $value];
			},
			'$type' => function($key, $value) {
				return ['$type' => (integer) $value];
			},
			'$mod' => function($key, $value) {
				$value = (array) $value;
				return ['$mod' => [current($value), next($value) ?: 0]];
			},
			'$size' => function($key, $value) {
				return ['$size' => (integer) $value];
			},
			'$elemMatch' => function($operator, $values, $options = []) {
				$options += [
					'castOpts' => [],
					'field' => ''
				];
				$options['castOpts'] += ['pathKey' => $options['field']];
				$values = (array) $values;

				if (empty($options['castOpts']['schema'])) {
					return ['$elemMatch' => $values];
				}
				foreach ($values as $key => &$value) {
					$value = $options['castOpts']['schema']->cast(
						null, $key, $value, $options['castOpts']
					);
				}
				return ['$elemMatch' => $values];
			}
		];
	}
1000960
function select($fields=NULL,$filter=NULL,array $options=NULL,$ttl=0) {
		if (!$options)
			$options=[];
		$options+=[
			'group'=>NULL,
			'order'=>NULL,
			'limit'=>0,
			'offset'=>0
		];
		$tag='';
		if (is_array($ttl))
			list($ttl,$tag)=$ttl;
		$fw=\Base::instance();
		$cache=\Cache::instance();
		if (!($cached=$cache->exists($hash=$fw->hash($this->db->dsn().
			$fw->stringify([$fields,$filter,$options])).($tag?'.'.$tag:'').'.mongo',
			$result)) || !$ttl || $cached[0]+$ttl<microtime(TRUE)) {
			if ($options['group']) {
				$grp=$this->collection->group(
					$options['group']['keys'],
					$options['group']['initial'],
					$options['group']['reduce'],
					[
						'condition'=>$filter,
						'finalize'=>$options['group']['finalize']
					]
				);
				$tmp=$this->db->selectcollection(
					$fw->HOST.'.'.$fw->BASE.'.'.
					uniqid(NULL,TRUE).'.tmp'
				);
				$tmp->batchinsert($grp['retval'],['w'=>1]);
				$filter=[];
				$collection=$tmp;
			}
			else {
				$filter=$filter?:[];
				$collection=$this->collection;
			}
			if ($this->legacy) {
				$this->cursor=$collection->find($filter,$fields?:[]);
				if ($options['order'])
					$this->cursor=$this->cursor->sort($options['order']);
				if ($options['limit'])
					$this->cursor=$this->cursor->limit($options['limit']);
				if ($options['offset'])
					$this->cursor=$this->cursor->skip($options['offset']);
				$result=[];
				while ($this->cursor->hasnext())
					$result[]=$this->cursor->getnext();
			}
			else {
				$this->cursor=$collection->find($filter,[
					'sort'=>$options['order'],
					'limit'=>$options['limit'],
					'skip'=>$options['offset']
				]);
				$result=$this->cursor->toarray();
			}
			if ($options['group'])
				$tmp->drop();
			if ($fw->CACHE && $ttl)
				// Save to cache backend
				$cache->set($hash,$result,$ttl);
		}
		$out=[];
		foreach ($result as $doc)
			$out[]=$this->factory($doc);
		return $out;
	}
1170060
protected function fetchData()
    {
        if ($this->_iterator === null) {
            if (empty($this->query->orderBy)) {
                // setting cursor batch size may setup implicit limit on the query with 'sort'
                // @see https://jira.mongodb.org/browse/PHP-457
                $this->query->addOptions(['batchSize' => $this->batchSize]);
            }
            $cursor = $this->query->buildCursor($this->db);
            $token = 'fetch cursor id = ' . $cursor->getId();
            Yii::info($token, __METHOD__);

            if ($cursor instanceof \Iterator) {
                $this->_iterator = $cursor;
            } else {
                $this->_iterator = new \IteratorIterator($cursor);
            }

            $this->_iterator->rewind();
        }

        $rows = [];
        $count = 0;

        while ($count++ < $this->batchSize) {
            $row = $this->_iterator->current();
            if ($row === null) {
                break;
            }
            $this->_iterator->next();
            //var_dump($row);
            $rows[] = $row;
        }
        return $this->query->populate($rows);
    }
53317
protected function collection_query( &$collection ) 
	{
		$local_keys = array();
		
		foreach( $collection as $item )
		{
			$local_keys[] = $item->raw( $this->local_key );
		}
		
		// set the correct collection where
		$this->query->wheres = array();
		$this->query->where( $this->foreign_key, 'in', $local_keys );
		$this->query->group_result( $this->foreign_key );
		
		$this->query->limit( null );
	}
1300093
public function initialize()
    {
        if ($this->mongoClient !== null) {
            return;
        }

        if ($this->eventManager->hasListeners(Events::preConnect)) {
            $this->eventManager->dispatchEvent(Events::preConnect, new EventArgs($this));
        }

        $server = $this->server ?: 'mongodb://localhost:27017';
        $options = $this->options;

        $options = isset($options['timeout']) ? $this->convertConnectTimeout($options) : $options;
        $options = isset($options['wTimeout']) ? $this->convertWriteTimeout($options) : $options;

        $this->mongoClient = $this->retry(function() use ($server, $options) {
            return new \MongoClient($server, $options, $this->driverOptions);
        });

        if ($this->eventManager->hasListeners(Events::postConnect)) {
            $this->eventManager->dispatchEvent(Events::postConnect, new EventArgs($this));
        }
    }
1215151
public function current()
    {
        $documentData = $this->myResultCursor->current();
        if (is_null($documentData)) {
            return null; 
        }
        /** @var MongoObject $document */
        $document = $this->container->get(
            $this->classMapInterface->getClassForResult($this->collection, $documentData)
        );

        $document->setCollection($this->collection);
        $document->loadFromArray($documentData);

        return $document;
    }
653820
public function getFieldTypes()
    {
        static $cached = [];

        $class = static::class;

        if (!isset($cached[$class])) {
            if (!$doc = static::sample()) {

                if (!$docs = $this->getConnection()->fetchAll($this->getSource(), [], ['limit' => 1])) {
                    throw new RuntimeException(['`:collection` collection has none record', 'collection' => $this->getSource()]);
                }
                $doc = $docs[0];
            }

            $types = [];
            foreach ($doc as $field => $value) {
                $type = gettype($value);
                if ($type === 'integer') {
                    $types[$field] = 'int';
                } elseif ($type === 'string') {
                    $types[$field] = 'string';
                } elseif ($type === 'double') {
                    $types[$field] = 'float';
                } elseif ($type === 'boolean') {
                    $types[$field] = 'bool';
                } elseif ($type === 'array') {
                    $types[$field] = 'array';
                } elseif ($value instanceof ObjectID) {
                    if ($field === '_id') {
                        continue;
                    }
                    $types[$field] = 'objectid';
                } else {
                    throw new RuntimeException(['`:field` field value type can not be infered.', 'field' => $field]);
                }
            }

            $cached[$class] = $types;
        }

        return $cached[$class];
    }
603274
protected function getData()
    {
        $data = [];
        foreach ($this->_schema as $name => $desc) {
            $data[$name] = $this->$name;
            if (isset($desc['updateDate']) && $desc['updateDate']) {
                $data[$name] = new MongoDate();
            }
        }
        if ($data['_id'] === null) {
            // @codeCoverageIgnoreStart
            unset($data['_id']);
            // @codeCoverageIgnoreEnd
        }
        return $data;
    }
366982
function update() {
		$pkey=['_id'=>$this->document['_id']];
		if (isset($this->trigger['beforeupdate']) &&
			\Base::instance()->call($this->trigger['beforeupdate'],
				[$this,$pkey])===FALSE)
			return $this->document;
		$upsert=['upsert'=>TRUE];
		if ($this->legacy)
			$this->collection->update($pkey,$this->document,$upsert);
		else
			$this->collection->replaceone($pkey,$this->document,$upsert);
		if (isset($this->trigger['afterupdate']))
			\Base::instance()->call($this->trigger['afterupdate'],
				[$this,$pkey]);
		return $this->document;
	}