@param null|string $databaseId
@param null|string $context
@param null        $collectionId
@param array       $fields

@return string
@throws InvalidArgumentException
545702
protected function getDatabaseSnapshotUrl($databaseId = null, $context = null, $collectionId = null, $fields = [])
    {
        if ($context) {
            $this->setContext($context);
        }
        if ($databaseId) {
            $this->setDatabaseId($databaseId);
        }

        $params = [];
        if ($collectionId) {
            $params['collection_id'] = $collectionId;
        }
        if ($fields) {
            $params['fields'] = implode(',', $fields);
        }

        return $this->serviceScheme . '://' . $this->serviceDomain . '/' . $this->version . '/data/'
        . $this->getContext() . '/databases/' . $this->getDatabaseId() . '/snapshot/?' . http_build_query($params);
    }
802639
function getNextId(db, collectionName, fieldName, callback) {
    if (typeof fieldName == "function") {
        callback = fieldName;
        fieldName = null;
    }

    fieldName = fieldName || getOption(collectionName, "field");
    var collection = db.collection(defaultSettings.collection);
    var step = getOption(collectionName, "step");

    collection.findAndModify(
        {_id: collectionName, field: fieldName},
        null,
        {$inc: {seq: step}},
        {upsert: true, new: true},
        function (err, result) {
            if (err) {
                if (err.code == 11000) {
                    process.nextTick(getNextId.bind(null, db, collectionName, fieldName, callback));
                } else {
                    callback(err);
                }
            } else {
                if (result.value && result.value.seq) {
                    callback(null, result.value.seq);
                } else {
                    callback(null, result.seq);
                }
            }
        }
    );
}
892302
public static String getDocumentLink(final String databaseName, final String collectionName, final String documentId) {
        return getCollectionLink(databaseName, collectionName) + "/docs/" + documentId;
    }
675054
public static function getQueryBuilder(String $connectionId=null)
	{
		if ($connectionId == null) {
			$connectionId = Repository::$staticConnectionId;
		}

		return self::getInstance($connectionId)->provider->queryBuilder(new ConnectionManager(), $connectionId);
	}
121245
protected function generateCriteria($key, $value, $collectionName, $dataBase)
    {
        $map = new \MongoCode(
            "function() {
                    for (var key in eval('this.' + preColumn)) {
                        emit(preColumn + '.' + key, null);
                    }
            }"
        );
        $reduce = new \MongoCode("function(k, vals) {  return null; }");

        preg_match('/(.*)\.\*/',$key, $column);
        $preColumnn = $column[1];

        $commandResult = $dataBase->command(array(
            "mapreduce" => $collectionName,
            "map" => $map,
            "reduce" => $reduce,
            "out" => array("inline" => 1),
            "scope" => array(
                "preColumn" => "$preColumnn"
            )
        ));

        $criteria = array();
        if (is_array($commandResult) && array_key_exists('ok', $commandResult ) && $commandResult['ok'] == 1) {
            foreach ($commandResult['results'] as $filter) {
                $criteria[] = array($filter['_id'] => $value);
            }
        }

        return $criteria;
    }
242702
protected function getDBField($field)
    {
        $dbField = null;
        if (stristr($field, self::SEPARATOR) !== false) {
            list ($relationName, $relationField) = explode(self::SEPARATOR, $field);
            $class = $this->getDataObjectInstance()->getRelationClass($relationName);
            if (!$class) {
                throw new InvalidArgumentException(sprintf(
                    'Could not find relation %s on %s',
                    $relationName,
                    $this->getDataObjectClass()
                ));
            }
            return Injector::inst()->get($class)->dbObject($relationField);
        }

        return $this->getDataObjectInstance()->dbObject($field);
    }
67706
public function mapToCollection(CollectionType $collectionType, callable $mapperCallback = null, callable $reverseMapperCallback = null)
    {
        $collectionClass = $collectionType->getCollectionClass();

        if ($collectionClass === TypedCollection::class || $collectionClass === ITypedCollection::class) {
            $collectionFactory = function (array $input) use ($collectionType) {
                return new TypedCollection($collectionType->getElementType(), $input);
            };
        } elseif ($collectionClass === EntityIdCollection::class) {
            $collectionFactory = function (array $input) use ($collectionType) {
                return new EntityIdCollection($input);
            };
        } elseif ($collectionType->isSubsetOf(TypedObject::collectionType())) {
            $objectType = $collectionType->getElementType()->asTypeString();
            $collectionFactory = function (array $input) use ($objectType) {
                /** @var string|TypedObject $objectType */
                return $objectType::collection($input);
            };
        } else {
            throw InvalidArgumentException::format(
                'Invalid collection type supplied to %s: expecting one of (%s), %s given',
                get_class($this) . '::' . __FUNCTION__,
                Debug::formatValues([TypedCollection::class, EntityIdCollection::class, TypedObject::collectionType()->asTypeString()]),
                $collectionType->asTypeString()
            );
        }

        $this->customProcessorCallbacks[] = function (IType $currentType) use (
            $collectionType,
            $collectionFactory,
            $mapperCallback,
            $reverseMapperCallback
        ) {
            return new CustomProcessor(
                $currentType->isNullable() ? $collectionType->nullable() : $collectionType,
                function (array $elements) use ($collectionFactory, $mapperCallback) {
                    $elements = $mapperCallback ? array_map($mapperCallback, $elements) : $elements;

                    return $collectionFactory($elements);
                },
                function (ITypedCollection $collection) use ($collectionType, $reverseMapperCallback) {
                    $elements = [];

                    foreach ($collection as $key => $element) {
                        $elements[$key] = $element;
                    }

                    return $reverseMapperCallback ? array_map($reverseMapperCallback, $elements) : $elements;
                }
            );
        };

        return $this;
    }
1117453
protected function getDatabaseDeltasUrl(
        $databaseId = null,
        $context = null,
        $fields = [],
        $baseRevision = null,
        $limit = null
    ) {
        if ($context) {
            $this->setContext($context);
        }
        if ($databaseId) {
            $this->setDatabaseId($databaseId);
        }
        $params = [];
        if ($baseRevision !== null) {
            $params['base_revision'] = $baseRevision;
        }
        if ($limit) {
            $params['limit'] = $limit;
        }
        if ($fields) {
            $params['fields'] = implode(',', $fields);
        }

        return $this->serviceScheme . '://' . $this->serviceDomain . '/' . $this->version . '/data/'
        . $this->getContext() . '/databases/' . $this->getDatabaseId() . '/deltas?' . http_build_query($params);
    }
316710
public function listCommand($services = [], $collection_pattern = '', $field = '', $db = [])
    {
        foreach ($this->_getServices($services) as $service) {
            /**
             * @var \ManaPHP\Mongodb $mongodb
             */
            $mongodb = $this->_di->getShared($service);

            $defaultDb = $mongodb->getDefaultDb();
            foreach ($defaultDb ? [$defaultDb] : $mongodb->listDatabases() as $cdb) {
                if ($db && !in_array($cdb, $db, true)) {
                    continue;
                }

                $this->console->writeLn(['---`:db` db of `:service` service---', 'db' => $cdb, 'service' => $service], Console::BC_CYAN);
                foreach ($mongodb->listCollections($cdb) as $row => $collection) {
                    if ($collection_pattern && !fnmatch($collection_pattern, $collection)) {
                        continue;
                    }
                    if ($field) {
                        if (!$docs = $mongodb->fetchAll("$cdb.$collection", [$field => ['$exists' => 1]], ['limit' => 1])) {
                            continue;
                        }
                    } else {
                        $docs = $mongodb->fetchAll("$cdb.$collection", [], ['limit' => 1]);
                    }
                    $columns = $docs ? array_keys($docs[0]) : [];

                    $this->console->writeLn([' :row :namespace(:columns)',
                        'row' => sprintf('%2d ', $row + 1),
                        'namespace' => $this->console->colorize("$cdb.$collection", Console::FC_GREEN),
                        'columns' => implode(', ', $columns)]);
                }
            }
        }
    }
1155605
public function mapCollection(\Iterator $collection, $expression = null, $context = null)
    {
        foreach ($collection as $key => $record) {
            if (!is_array($record)) {
                throw new InvalidRecordException('Record must be an array.');
            }

            yield $key => $expression !== null
                ? $this->mapMapping($record, $expression, $context, $key)
                : $record;
        }
    }
765905
static public function createObjectID($id=null)
    {
        if ($id === null) {
            return new \MongoDB\BSON\ObjectId;
        }

        try {
            return new \MongoDB\BSON\ObjectId($id);
        } catch(\MongoDB\Driver\Exception\InvalidArgumentException $e) {
        }

        throw new Exception('Invalid ObjectId');
    }
144308
public <R, RK> List<R> fetch(Collection<DBRef<R, RK>> collection, DBObject fields) {
        Map<JacksonCollectionKey, List<Object>> collectionsToIds = new HashMap<JacksonCollectionKey, List<Object>>();
        for (DBRef<R, RK> ref : collection) {
            if (ref instanceof FetchableDBRef) {
                JacksonCollectionKey key = ((FetchableDBRef) ref).getCollectionKey();
                List<Object> ids = collectionsToIds.get(key);
                if (ids == null) {
                    ids = new ArrayList<Object>();
                    collectionsToIds.put(key, ids);
                }
                ids.add(getReferenceCollection(key).convertToDbId(ref.getId()));
            }
        }
        List<R> results = new ArrayList<R>();
        for (Map.Entry<JacksonCollectionKey, List<Object>> entry : collectionsToIds.entrySet()) {
            for (R result : this.<R, RK>getReferenceCollection(entry.getKey()).find(
                    new QueryBuilder().put("_id").in(entry.getValue()).get(), fields)) {
                results.add(result);
            }
        }
        return results;
    }
416988
protected function normalizeCollection($collection, $name, $format = null, array $context = array())
    {
        if (empty($collection)) {
            return array();
        }

        if ($collection instanceof AbstractLazyCollection and !$collection->isInitialized()) {
            return array();
        }

        $data = array();
        foreach ($collection as $key => $element) {
            $data[$key] = $this->normalizeAssociation($element, $name, $format, $context);
        }

        return $data;
    }
244607
public function getRecord($tableName, $field, $value, $fields = array())
    {
        try {
            return $this->db->getRecord($tableName, $field, $value, $fields);
        } catch (\Exception $e) {
            throw new DbException($e->getMessage());
        }
    }
185555
public function setDbCollection(string $dbName, string $collectionName): \MongoCollection
    {
        return $this->mongoClient->selectDB($dbName)->selectCollection($collectionName);
    }
1073573
public static function createFromLocalId(Connection $dbal, $localId)
    {
        $data = $dbal->fetchAll(
            'SELECT T.*
                                               FROM '.self::PERSIST_TABLE.' AS T
                             INNER JOIN '.self::PERSIST_TABLE.' AS S ON T.shop_order_id = S.shop_order_id
                                  WHERE S.`local_id` = ?
                               ORDER BY T.`cmsident`
                                  ',
            array($localId)
        );
        $manager = self::createFromRecordList($data);

        if (null === $manager) {
            throw new \InvalidArgumentException("unable to find an an id mapper object based on the local reference id [{$localId}]");
        }

        return $manager;
    }
1057585
public function getCollection($collectionId, $includeAllItems = false)
    {
        if (!$this->apiVersionIsGreaterThanV3()) {
            throw new EndpointNotSupportedByApiVersionException();
        }

        if (!is_bool($includeAllItems)) {
            throw new InvalidTypeException('Include All Items', 'boolean', gettype($includeAllItems));
        }

        $params = [
            'includeAllItems' => $includeAllItems,
        ];

        return $this->get(sprintf('collections/%s/items', $collectionId), $params);
    }