Overwrites given document with given id.
@param {string} db
@param {string} id
@param {Object} doc
@param {Object} metadata
@param {Function} cb
511702
function (db, id, doc, metadata, cb) {
			var operations = [
				{
					Method: "PUT",
					Document: doc,
					Metadata: metadata,
					Key: id
				}
			];
			request.post({
				url: host + 'databases/' + db + '/bulk_docs',
				headers: {
					'Content-Type': 'application/json; charset=utf-8'
				},
				body: JSON.stringify(operations)
			}, function (error, response, resBody) {
				if (!error && response.statusCode === 200) {
					var result = JSON.parse(resBody);
					cb(null, result);
				} else {
					cb(error || new Error(response.statusCode), null);
				}
			});
		}
296365
public WriteResult<T, K> updateById(K id, DBUpdate.Builder update) throws MongoException {
        return this.update(createIdQuery(id), update.serialiseAndGet(objectMapper));
    }
211700
function(db, id) {
        this._db = db;
        this._id = id;
        this._points = {};
        this._size = 0;
        this._changed = false;
    }
1312935
function(doc, callback) {
        audit([doc], 'delete', function(err) {
          if (err) {
            return callback(err);
          }
          docsDb.removeDoc(doc._id, doc._rev, callback);
        });
      }
911267
function update(id, body, cb) {
  body.updated_at = new Date();

  var q = qb.update(id, body);
  db.getClient(function(err, client, done) {
    client.query(q[0], q[1], function(err, r) {
      var result = r && r.rows[0];
      if(!err && !result) { err = new exceptions.NotFound(); }
      if(err) {
        cb(err);
        done(err);
      } else {
        cb(null, result);
        done();
      }
    });
  });
}
472618
function (doc) {
    var self = this;
    var id = doc._id;
    if (self._published.has(id))
      throw Error("tried to add something already published " + id);
    if (self._limit && self._unpublishedBuffer.has(id))
      throw Error("tried to add something already existed in buffer " + id);

    var limit = self._limit;
    var comparator = self._comparator;
    var maxPublished = (limit && self._published.size() > 0) ?
      self._published.get(self._published.maxElementId()) : null;
    var maxBuffered = (limit && self._unpublishedBuffer.size() > 0) ?
      self._unpublishedBuffer.get(self._unpublishedBuffer.maxElementId()) : null;
    // The query is unlimited or didn't publish enough documents yet or the new
    // document would fit into published set pushing the maximum element out,
    // then we need to publish the doc.
    var toPublish = ! limit || self._published.size() < limit ||
                    comparator(doc, maxPublished) < 0;

    // Otherwise we might need to buffer it (only in case of limited query).
    // Buffering is allowed if the buffer is not filled up yet and all matching
    // docs are either in the published set or in the buffer.
    var canAppendToBuffer = !toPublish && self._safeAppendToBuffer &&
                            self._unpublishedBuffer.size() < limit;

    // Or if it is small enough to be safely inserted to the middle or the
    // beginning of the buffer.
    var canInsertIntoBuffer = !toPublish && maxBuffered &&
                              comparator(doc, maxBuffered) <= 0;

    var toBuffer = canAppendToBuffer || canInsertIntoBuffer;

    if (toPublish) {
      self._addPublished(id, doc);
    } else if (toBuffer) {
      self._addBuffered(id, doc);
    } else {
      // dropping it and not saving to the cache
      self._safeAppendToBuffer = false;
    }
  }
52395
function(name, doc, fromMessage, res) {
            var id   = this.toId(doc._id, true);
            if (typeof id === 'undefined' || id === '') {
                return res.send(400, "invalid id.");
            }
            doc._id  = id;
            doc._time = new Date().getTime();

            var collection = new mongodb.Collection(this.db, name);
            collection.insert(
                doc,
                {safe:true},
                function(err, docs) {
                    if(err) {
                        res.send(400, err);
                    } else {
                        var doc = docs && docs.length > 0 ? docs[0] : null;
                        if (doc) {
                            var msg = {
                                method: 'create',
                                id: doc._id,
                                time: doc._time,
                                data: doc
                            };
                            rest.onSuccess(name, msg, fromMessage);
                            res.send(doc);
                        } else {
                            res.send(400, 'failed to create document.');
                        }
                    }
                }
            );
        }
634381
def write_back(self, documents, doc_ids=None, eids=None):
        
        doc_ids = _get_doc_ids(doc_ids, eids)

        if doc_ids is not None and not len(documents) == len(doc_ids):
            raise ValueError(
                'The length of documents and doc_ids is not match.')

        if doc_ids is None:
            doc_ids = [doc.doc_id for doc in documents]

        # Since this function will write docs back like inserting, to ensure
        # here only process existing or removed instead of inserting new,
        # raise error if doc_id exceeded the last.
        if len(doc_ids) > 0 and max(doc_ids) > self._last_id:
            raise IndexError(
                'ID exceeds table length, use existing or removed doc_id.')

        data = self._read()

        # Document specified by ID
        documents.reverse()
        for doc_id in doc_ids:
            data[doc_id] = dict(documents.pop())

        self._write(data)

        return doc_ids
597960
public void purge(@NonNull Document document) throws CouchbaseLiteException {
        if (document == null) { throw new IllegalArgumentException("document cannot be null."); }

        if (document.isNewDocument()) {
            throw new CouchbaseLiteException("Document doesn't exist in the database.",
                CBLError.Domain.CBLITE, CBLError.Code.NOT_FOUND);
        }

        synchronized (lock) {
            prepareDocument(document);

            boolean commit = false;
            beginTransaction();
            try {
                // revID: null, all revisions are purged.
                if (document.getC4doc().purgeRevision(null) >= 0) {
                    document.getC4doc().save(0);
                    // Reset c4doc:
                    document.replaceC4Document(null);
                    commit = true;
                }
            }
            catch (LiteCoreException e) {
                throw CBLStatus.convertException(e);
            }
            finally {
                endTransaction(commit);
            }
        }
    }
846184
public void document_id_DELETE(String id) throws IOException {
		String qPath = "/me/document/{id}";
		StringBuilder sb = path(qPath, id);
		exec(qPath, "DELETE", sb.toString(), null);
	}
629169
private void updateDocument(EntityMetadata metadata, final MetamodelImpl metaModel, Object entity, String parentId,
            Class<? extends Object> class1, boolean b)
    {
        updateOrCreateIndex(metadata, metaModel, entity, parentId, entity.getClass(), true);
        onCommit();
    }
1303343
public function addDocument($doc, $id = null)
    {
        $action = array(
            self::BULK_ACTION => array(
                '_id' => $id,
                '_index' => $this->index,
                '_type' => $this->type
            )
        );

        $this->body .= json_encode($action) . self::LINE_BREAK;
        $this->body .= $this->serializer->serialize($doc, $this->serializerParams) . self::LINE_BREAK;
    }
162644
public function update($id, array &$doc)
    {
        $json = JSONEncoder::encode($doc);

        $response = $this->client->request('PUT', "/{$this->name}/{$id}", [
            'body'    => $json,
            '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'];
    }
1180072
function _update(query, op, criteria, doc, options, force, callback) {
  query.op = op;

  if (Query.canMerge(criteria)) {
    query.merge(criteria);
  }

  if (doc) {
    query._mergeUpdate(doc);
  }

  if (utils.isObject(options)) {
    // { overwrite: true }
    query.setOptions(options);
  }

  // we are done if we don't have callback and they are
  // not forcing an unsafe write.
  if (!(force || callback)) {
    return query;
  }

  if (!query._update ||
      !query.options.overwrite && 0 === utils.keys(query._update).length) {
    callback && utils.soon(callback.bind(null, null, 0));
    return query;
  }

  options = query._optionsForExec();
  if (!callback) options.safe = false;

  criteria = query._conditions;
  doc = query._updateForExec();

  debug('update', query._collection.collectionName, criteria, doc, options);
  callback = query._wrapCallback(op, callback, {
    conditions: criteria,
    doc: doc,
    options: options
  });

  query._collection[op](criteria, doc, options, utils.tick(callback));

  return query;
}
1353022
private InternalDocumentRevision createDocumentBody(SQLDatabase db, String docId, final DocumentBody
            body)
            throws AttachmentException, ConflictException, DocumentStoreException {
        Misc.checkState(this.isOpen(), "Database is closed");
        CouchUtils.validateDocumentId(docId);
        Misc.checkNotNull(body, "Input document body");
        this.validateDBBody(body);

        // check if the docid exists first:

        // if it does exist:
        // * if winning leaf deleted, root the 'created' document there
        // * else raise error
        // if it does not exist:
        // * normal insert logic for a new document

        InsertRevisionCallable callable = new InsertRevisionCallable();
        InternalDocumentRevision potentialParent = null;

        try {
            potentialParent = new GetDocumentCallable(docId, null, this.attachmentsDir, this.attachmentStreamFactory).call(db);
        } catch (DocumentNotFoundException e) {
            //this is an expected exception, it just means we are
            // resurrecting the document
        }

        if (potentialParent != null) {
            if (!potentialParent.isDeleted()) {
                // current winner not deleted, can't insert
                throw new ConflictException(String.format("Cannot create doc, document with id %s" +
                        " already exists "
                        , docId));
            }
            // if we got here, parent rev was deleted
            new SetCurrentCallable(potentialParent.getSequence(), false).call(db);
            callable.revId = CouchUtils.generateNextRevisionId(potentialParent.getRevision());
            callable.docNumericId = potentialParent.getInternalNumericId();
            callable.parentSequence = potentialParent.getSequence();
        } else {
            // otherwise we are doing a normal create document
            long docNumericId = new InsertDocumentIDCallable(docId).call(db);
            callable.revId = CouchUtils.getFirstRevisionId();
            callable.docNumericId = docNumericId;
            callable.parentSequence = -1l;
        }
        callable.deleted = false;
        callable.current = true;
        callable.data = body.asBytes();
        callable.available = true;
        callable.call(db);

        try {
            InternalDocumentRevision doc = new GetDocumentCallable(docId, callable.revId, this.attachmentsDir, this.attachmentStreamFactory).call(db);
            logger.finer("New document created: " + doc.toString());
            return doc;
        } catch (DocumentNotFoundException e) {
            throw new RuntimeException(String.format("Could not get document we just inserted " +
                    "(id: %s); this should not happen, please file an issue with as much detail " +
                    "as possible.", docId), e);
        }

    }
264458
function (db, entityName, doc, cb) {
			request.post({
				url: host + 'databases/' + db + '/docs',
				headers: {
					'Content-Type': 'application/json; charset=utf-8',
					'Raven-Entity-Name': entityName
				},
				body: JSON.stringify(doc)
			}, function (error, response, resBody) {
				if (!error && (response.statusCode === 201 || response.statusCode === 200)) {
					var result = JSON.parse(resBody);
					cb(null, result);
				} else {
					cb(error || new Error(response.statusCode), null);
				}
			});
		}
535537
def update_ids(self, docids):
        """"""
        logger.info("updating %i id mappings" % len(docids))
        for docid in docids:
            if docid is not None:
                pos = self.id2pos.get(docid, None)
                if pos is not None:
                    logger.info("replacing existing document %r in %s" % (docid, self))
                    del self.pos2id[pos]
                self.id2pos[docid] = self.length
                try:
                    del self.id2sims[docid]
                except:
                    pass
            self.length += 1
        self.id2sims.sync()
        self.update_mappings()