@param string $source
@param array  $documents
@param string $primaryKey

@return int
@throws \ManaPHP\Mongodb\Exception
198167
public function bulkUpsert($source, $documents, $primaryKey)
    {
        $namespace = strpos($source, '.') !== false ? $source : ($this->_default_db . '.' . $source);

        $this->eventsManager->fireEvent('mongodb:beforeBulkUpsert', $this, ['namespace' => $namespace]);

        /** @var \ManaPHP\Mongodb\ConnectionInterface $connection */
        $connection = $this->poolManager->pop($this);
        try {
            $count = $connection->bulkUpsert($namespace, $documents, $primaryKey);
        } finally {
            $this->poolManager->push($this, $connection);
        }
        $this->eventsManager->fireEvent('mongodb:afterBulkUpsert', $this);

        $this->logger->info(compact('count', 'namespace', 'documents'), 'mongodb.bulk.upsert');
        return $count;
    }
1239585
public function setPrimaryKey( $key )
	{
		if( in_array( $key, $this->fields ) )
		{
			$this->primaryKey = $key;
			return TRUE;
		}
		return FALSE;
	}
522192
public function update($primaryKeyValue, $fieldsValues)
    {
        $this->connectToDB();
        $this->queryBuilder->table($this->table());
        $this->primaryKeyWhere($primaryKeyValue);
        $this->queryBuilder->update($fieldsValues);
        return $primaryKeyValue;
    }
897443
public function setDocuments(array $documents)
    {
        if ($documents instanceof PagSeguroDocument) {
            $this->documents = $documents;
        } else {
            if (is_array($documents)) {
                $this->addDocument($documents['type'], $documents['value']);
            }
        }
    }
695479
public function parse(Source $source, array $options = []): DocumentNode
    {
        $this->lexer = $this->createLexer($source, $options);

        return $this->lexDocument();
    }
696800
public function ignore($id, $primaryKey = 'id')
    {
        $this->ignore = $id;
        $this->primaryKey = $primaryKey;

        return $this;
    }
927444
public function update(Entity $entity, $primaryValue)
    {
        if (!$entity->getValidator()->validate()) {
            throw new Exception\ValidatorException($entity->getValidator());
        }

        try {

            if (!$this->query()->updateOne($primaryValue, $entity->getData())->run($this->connection)) {
                throw new Exception\RepositoryException("Entity was not successfully updated!");
            }
        } catch (Exception\QueryException $e) {
            throw new Exception\RepositoryException($e->getMessage());
        }

        $this->_saveAssociated($primaryValue, $entity);
    }
519667
public function createDocumentTermCount($documents)
    {
        $termCount = new TermCount($this->getSearchDbHandle(), $documents, $this->filters, $this->storage);
        $termCount->execute();
    }
774308
private function executeReorders($documents)
    {
        foreach ($documents as $oid => $list) {
            if (!$this->contains($oid)) {
                continue;
            }
            foreach ($list as $value) {
                list($parent, $src, $target, $before) = $value;
                $parentNode = $this->session->getNode($this->getDocumentId($parent));

                // check for src and target ...
                $dest = $target;
                if ($parentNode->hasNode($src) && $parentNode->hasNode($target)) {
                    // there is no orderAfter, so we need to find the child after target to use it in orderBefore
                    if (!$before) {
                        $dest = null;
                        $found = false;
                        foreach ($parentNode->getNodes() as $name => $child) {
                            if ($name === $target) {
                                $found = true;
                            } elseif ($found) {
                                $dest = $name;
                                break;
                            }
                        }
                    }

                    $parentNode->orderBefore($src, $dest);
                    $class = $this->dm->getClassMetadata(get_class($parent));
                    foreach ($class->childrenMappings as $fieldName) {
                        if ($parent instanceof Proxy && $parent->__isInitialized()) {
                            $children = $class->reflFields[$fieldName]->getValue($parent);
                            $children->refresh();
                        }
                    }
                }
            }
        }
    }
471511
public function upsert($namespace, $document, $primaryKey)
    {
        $bulk = new BulkWrite();

        try {
            $bulk->update([$primaryKey => $document[$primaryKey]], $document, ['upsert' => true]);
        } catch (\Exception $exception) {
            throw new MongodbException($exception->getMessage(), $exception->getCode(), $exception);
        }

        return $this->bulkWrite($namespace, $bulk)->getUpsertedCount();
    }
419062
public function getByRef(array $ref, array $parentEntity = [])
    {
        $document = $parentEntity;
        if (strpos($ref['rootDocumentEntityType'], 'parent') === false) {
            if (empty($document['_id']) || $document['_id'] !== $ref['rootDocumentId']) {
                $document = $this->getById($ref['rootDocumentEntityType'], $ref['rootDocumentId']);
            }

            if (count($document) === 0) {
                throw new Exception('Invalid document reference (document cannot be found by Id)');
            }
        }

        $container = $document;
        foreach ($ref['path'] as $pathInDocument) {
            if (!array_key_exists($pathInDocument['field'], $container)) {
                throw new Exception('Could not find the path in document');
            }
            $container = $container[$pathInDocument['field']];
            if (empty($pathInDocument['objectId'])) {
                continue;
            }

            if (!is_array($container)) {
                throw new Exception('Invalid value for path in document');
            }
            $result = array_filter($container, function ($item) use ($pathInDocument) {
                return $item['_id'] === $pathInDocument['objectId'];
            });
            if (count($result) === 0) {
                throw new Exception('Empty result of reference');
            }
            $container = reset($result);
        }
        return $container;
    }
932995
protected function _getIds(array $ids, $primaryKey = self::PRIMARY_KEY)
    {
        $return = [];
        foreach ($ids as $id => $value) {
            if (is_array($value) && is_int($id) && (int) $value[$primaryKey] === 1) {
                $return[$id] = $id;
            }
        }

        return $return;
    }
619787
public function insert($col, $doc = [], $cb = null, $params = [])
    {
        if (mb_orig_strpos($col, '.') === false) {
            $col = $this->dbname . '.' . $col;
        }

        if (!isset($doc['_id'])) {
            $doc['_id'] = new \MongoId;
        }
        if ($this->safeMode) {
            static::safeModeEnc($doc);
        }
        try {
            $this->request(
                self::OP_INSERT,
                "\x00\x00\x00\x00" . $col . "\x00" . bson_encode($doc),
                false,
                null,
                function ($conn, $reqId = null) use ($cb, $col, $params) {
                    if ($cb !== null) {
                        $this->lastError($col, $cb, $params, $conn);
                    }
                }
            );

            return $doc['_id'];
        } catch (\MongoException $e) {
            Daemon::log('MongoClient exception: ' . $e->getMessage() . ': ' . $e->getTraceAsString());
            if ($cb !== null) {
                if ($cb !== null) {
                    $cb(['$err' => $e->getMessage(), '$doc' => $doc]);
                }
            }
        }
    }
1840
protected function buildKeyedResultSet(array $results, string $primaryKey) : array
    {
        $builder = new EntityBuilder($this->mapper, array_keys($this->eagerLoads), $this->useCache);

        $keys = array_map(function ($item) use ($primaryKey) {
            return $item[$primaryKey];
        }, $results);

        return array_combine($keys, array_map(function ($item) use ($builder) {
            return $builder->build($item);
        }, $results));
    }
1169039
public function remove($primaryKey, $secondaryKey)
    {
        unset($this->values[$primaryKey][$secondaryKey]);

        if (isset($this->values[$primaryKey]) && 0 === count($this->values[$primaryKey])) {
            unset($this->values[$primaryKey]);
        }
    }
470347
public function bulkIndex(array $documents)
    {
        if (empty($documents)) {
            return;
        }

        $payload = '';
        foreach ($documents as $document) {
            $payload .= $this->serializer->getIndexMetadata($document) . "\n";
            $payload .= $this->serializer->getIndexDocument($document) . "\n";
        }

        $result = $this->client->request(
            'POST',
            "/{$this->indexName}/_bulk",
            new Message(
                array(
                    'Content-Type' => 'application/json',
                ),
                $payload
            )
        );

        if ($result->headers['status'] !== 201 && $result->headers['status'] !== 200) {
            throw new RuntimeException(
                'Wrong HTTP status received from Elasticsearch: ' . $result->headers['status']
            );
        }

        $this->flush();
    }
339510
protected function primaryKeyWhere($primaryKeyValue)
    {
        //value is not an array
        if(!is_array($primaryKeyValue)) {
            //turn value into array for first primary key field
            $primaryKeyValue = [
                $this->ORMParameters['primaryKey'][0] => $primaryKeyValue
            ];
        }
        //loop primary key fields
        foreach($this->ORMParameters['primaryKey'] as $field) {
            //check value
            if(!isset($primaryKeyValue[$field])) {
                throw new \Exception(sprintf('missing field % value in where clause for table %s compound primary key', $field, $this->table()));
            } else {
                $this->queryBuilder->where($field, $primaryKeyValue[$field]);
            }
        }
    }