Create or replace a document with the given ID

@param array $document Document to create. Must include `_id`  and `_type`
@param array $options Optional request options
@return array Returns the created document
9173
public function createOrReplace($document, $options = null)
    {
        $this->assertProperties($document, ['_id', '_type'], 'createOrReplace');
        return $this->createDocument($document, 'createOrReplace', $options);
    }
1115418
public function generate($document)
    {
        $lexer = new Lexer();
        $tokenStream = $lexer->tokenize($document);
        $tokenParser = new TokenParser();
        $nodeStream = $tokenParser->parse($tokenStream);
        $nodeParser = new NodeParser();
        $this->classBuilder = $nodeParser->parse($nodeStream);
        $compiler = new Compiler($this->options);
        $this->streamWriter = $compiler->compile($this->classBuilder);

        return $this;
    }
1023568
public function generate($document, ClassMetadata $cm, DocumentManagerInterface $dm, $parent = null)
    {
        $id = $cm->getFieldValue($document, $cm->identifier);
        if (!$id) {
            throw new IdException('ID could not be read from the document instance using the AssignedIdGenerator.');
        }

        return $id;
    }
921809
public function get_document($record, $options = array()) {
        try {
            $cm = $this->get_cm('book', $record->bookid, $record->courseid);
            $context = \context_module::instance($cm->id);
        } catch (\dml_missing_record_exception $ex) {
            // Notify it as we run here as admin, we should see everything.
            debugging('Error retrieving ' . $this->areaid . ' ' . $record->id . ' document, not all required data is available: ' .
                $ex->getMessage(), DEBUG_DEVELOPER);
            return false;
        } catch (\dml_exception $ex) {
            // Notify it as we run here as admin, we should see everything.
            debugging('Error retrieving ' . $this->areaid . ' ' . $record->id . ' document: ' . $ex->getMessage(), DEBUG_DEVELOPER);
            return false;
        }

        // Prepare associative array with data from DB.
        $doc = \core_search\document_factory::instance($record->id, $this->componentname, $this->areaname);
        $doc->set('title', content_to_text($record->title, false));
        $doc->set('content', content_to_text($record->content, $record->contentformat));
        $doc->set('contextid', $context->id);
        $doc->set('courseid', $record->courseid);
        $doc->set('owneruserid', \core_search\manager::NO_OWNER_ID);
        $doc->set('modified', $record->timemodified);

        // Check if this document should be considered new.
        if (isset($options['lastindexedtime']) && ($options['lastindexedtime'] < $record->timecreated)) {
            // If the document was created after the last index time, it must be new.
            $doc->set_is_new(true);
        }

        return $doc;
    }
778629
public function snapshot(DocumentReference $document, array $options = [])
    {
        return $this->createSnapshot($this->connection, $this->valueMapper, $document, [
            'transaction' => $this->transaction,
        ] + $options);
    }
685116
public function mDeleteDocument($documentIds, array $options = [])
    {
        if (!is_array($documentIds)) {
            throw new InvalidArgumentException('Collection.mDeleteDocument: documents parameter format is invalid (should be an array of document IDs)');
        }

        $data = ['body' => ['ids' => $documentIds]];

        $response = $this->kuzzle->query(
            $this->buildQueryArgs('document', 'mDelete'),
            $this->kuzzle->addHeaders($data, $this->headers),
            $options
        );

        return $response['result'];
    }
3466
public function delete(DocumentReference $document, array $options = [])
    {
        $this->writer->delete($document->name(), $options);

        return $this;
    }
119366
public function save(&$document) {

        return isset($document['_id']) ? $this->update(array('_id' => $document['_id']), $document) : $this->insert($document);
    }
797694
private function executeQuery($document, array $query, array $options)
    {
        $className  = get_class($document);
        $class      = $this->dm->getClassMetadata($className);
        $findQuery  = $this->getQueryForDocument($class, $document);
        $collection = $this->dm->getDocumentCollection($className);
        $collection->update($findQuery, $query, $options);
    }
1153061
protected function doInsert(array &$a, array $options)
    {
        $document = $a;
        $options = isset($options['safe']) ? $this->convertWriteConcern($options) : $options;
        $options = isset($options['wtimeout']) ? $this->convertWriteTimeout($options) : $options;
        $options = isset($options['timeout']) ? $this->convertSocketTimeout($options) : $options;
        $result = $this->mongoCollection->insert($document, $options);
        if (isset($document['_id'])) {
            $a['_id'] = $document['_id'];
        }
        return $result;
    }
412494
public function add_document($document, $fileindexing = false) {
        global $DB;

        $doc = (object)$document->export_for_engine();

        // Moodle's ids using DML are always autoincremented.
        $doc->docid = $doc->id;
        unset($doc->id);

        $id = $DB->get_field('search_simpledb_index', 'id', array('docid' => $doc->docid));
        try {
            if ($id) {
                $doc->id = $id;
                $DB->update_record('search_simpledb_index', $doc);
            } else {
                $DB->insert_record('search_simpledb_index', $doc);
            }

        } catch (\dml_exception $ex) {
            debugging('dml error while trying to insert document with id ' . $doc->docid . ': ' . $ex->getMessage(),
                DEBUG_DEVELOPER);
            return false;
        }

        return true;
    }
973858
public function create($index, $type, $document)
    {
        $request = $this->createRequestInstance(self::CREATE_DOCUMENT, $index, $type);
        $request->setBody($document);

        return $this->client->send($request);
    }
368885
public function insert(array &$doc)
    {
        if (isset($doc['_id'])) {
            $clone = $doc;
            unset($clone['_id']);

            $response = $this->client->request('PUT', "/{$this->name}/{$doc['_id']}", [
                'body'    => JSONEncoder::encode($clone),
                'headers' => ['Content-Type' => 'application/json'],
            ]);
        } else {
            $response = $this->client->request('POST', "/{$this->name}/", [
                'body'    => JSONEncoder::encode($doc),
                'headers' => ['Content-Type' => 'application/json'],
            ]);
        }

        if (201 !== $response->getStatusCode()) {
            throw new Exception('Unable to save document');
        }

        $value = JSONEncoder::decode((string) $response->getBody());

        $doc['_id'] = $value['id'];
        $doc['_rev'] = $value['rev'];
    }
867524
public function createDocument($document, $uid, $indexName = '', $indexType = '')
    {
        return new DocumentReference($document, $uid, $this->indexNamePrefix . $indexName, $indexType);
    }
306134
private function executeUpsert($document, array $options)
    {
        $options['upsert'] = true;
        $criteria = $this->getQueryForDocument($document);

        $data = $this->pb->prepareUpsertData($document);

        // Set the initial version for each upsert
        if ($this->class->isVersioned) {
            $versionMapping = $this->class->fieldMappings[$this->class->versionField];
            if ($versionMapping['type'] === 'int') {
                $nextVersion = max(1, (int) $this->class->reflFields[$this->class->versionField]->getValue($document));
                $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion);
            } elseif ($versionMapping['type'] === 'date') {
                $nextVersionDateTime = new \DateTime();
                $nextVersion = new \MongoDate($nextVersionDateTime->getTimestamp());
                $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersionDateTime);
            }
            $data['$set'][$versionMapping['name']] = $nextVersion;
        }

        foreach (array_keys($criteria) as $field) {
            unset($data['$set'][$field]);
        }

        // Do not send an empty $set modifier
        if (empty($data['$set'])) {
            unset($data['$set']);
        }

        /* If there are no modifiers remaining, we're upserting a document with
         * an identifier as its only field. Since a document with the identifier
         * may already exist, the desired behavior is "insert if not exists" and
         * NOOP otherwise. MongoDB 2.6+ does not allow empty modifiers, so $set
         * the identifier to the same value in our criteria.
         *
         * This will fail for versions before MongoDB 2.6, which require an
         * empty $set modifier. The best we can do (without attempting to check
         * server versions in advance) is attempt the 2.6+ behavior and retry
         * after the relevant exception.
         *
         * See: https://jira.mongodb.org/browse/SERVER-12266
         */
        if (empty($data)) {
            $retry = true;
            $data = array('$set' => array('_id' => $criteria['_id']));
        }

        try {
            $this->collection->update($criteria, $data, $options);
            return;
        } catch (\MongoCursorException $e) {
            if (empty($retry) || strpos($e->getMessage(), 'Mod on _id not allowed') === false) {
                throw $e;
            }
        }

        $this->collection->update($criteria, array('$set' => new \stdClass), $options);
    }
1269034
public function getDocument($collection, $id, array $options = [])
    {
        $this->setOptions($options);
        $doc = new Document($this->client, $this->database, $collection);
        $doc->setHeaders($this->getHeaders());
        $rs = $doc->get($id);
        $this->checkResponse($rs);
        unset($rs['_curl_info']);

        return $rs;
    }
30536
public function insertOne($document, array $options = [])
    {
        $model = new InsertOne($document);
        $bulkWriteResult = $this->bulkWrite([$model], $options);

        return new InsertOneResult($bulkWriteResult);
    }