replaces document identified by the primary_key or creates one if a matching document does not exist
495689
def update(self, table_name, primary_key, instance):
        
        assert isinstance(primary_key, dict)
        assert isinstance(instance, BaseDocument)
        collection = self._db[table_name]

        # work with a copy of the document, as the direct type change of the _id field
        # is later negated by the `BaseDocument.to_json` method
        document = instance.document
        if '_id' in document:
            document['_id'] = ObjectId(document['_id'])

        update_result = collection.replace_one(filter=primary_key, replacement=document, upsert=True)
        if update_result.upserted_id:
            instance['_id'] = update_result.upserted_id
        return update_result.upserted_id
1138979
function replaceRefObj (obj, resolvedValues, baseId, replaced) {
            // if found $ref key, other properties of the obj will be ignored
            if (obj.$ref) {
                var refId = url.resolve(baseId, obj.$ref);
                if (refId in resolvedValues) {
                    replaced[refId] = resolvedValues[refId];
                    return resolvedValues[refId];
                }
            }

            _.forOwn(obj, function(val, k) {
                if (!(val instanceof Object)) {
                    return true; //continue
                }

                var resolvedObj = replaceRefObj(val, resolvedValues, baseId, replaced);
                if (resolvedObj) {
                    obj[k] = resolvedObj;
                }
            });
        }
521978
def rename_index(self, old_name, new_name=None):
        
        old_name = self._normalize_identifier(old_name)
        normalized_new_name = self._normalize_identifier(new_name)

        if old_name == normalized_new_name:
            return self

        if not self.has_index(old_name):
            raise IndexDoesNotExist(old_name, self._name)

        if self.has_index(normalized_new_name):
            raise IndexAlreadyExists(normalized_new_name, self._name)

        old_index = self._indexes[old_name]

        if old_index.is_primary():
            self.drop_primary_key()

            return self.set_primary_key(old_index.get_columns(), new_name)

        del self._indexes[old_name]

        if old_index.is_unique():
            return self.add_unique_index(old_index.get_columns(), new_name)

        return self.add_index(old_index.get_columns(), new_name, old_index.get_flags())
955833
def insert(key, value):
    
    # Pickle the value.
    value = pickle.dumps(value, protocol=constants.PICKLE_PROTOCOL)
    # Store the value as binary data in a document.
    doc = {
        KEY_FIELD: key,
        VALUE_FIELD: Binary(value)
    }
    # Pickle and store the value with its key. If the key already exists, we
    # don't insert (since the key is a unique index), and we don't care.
    try:
        return collection.insert(doc)
    except pymongo.errors.DuplicateKeyError:
        return None
478311
def find_and_modify(self, query={}, update=None,
                        upsert=False, sort=None, full_response=False,
                        manipulate=False, **kwargs):
        
        warnings.warn("find_and_modify is deprecated, use find_one_and_delete"
                      ", find_one_and_replace, or find_one_and_update instead",
                      DeprecationWarning, stacklevel=2)

        if not update and not kwargs.get('remove', None):
            raise ValueError("Must either update or remove")

        if update and kwargs.get('remove', None):
            raise ValueError("Can't do both update and remove")

        # No need to include empty args
        if query:
            kwargs['query'] = query
        if update:
            kwargs['update'] = update
        if upsert:
            kwargs['upsert'] = upsert
        if sort:
            # Accept a list of tuples to match Cursor's sort parameter.
            if isinstance(sort, list):
                kwargs['sort'] = helpers._index_document(sort)
            # Accept OrderedDict, SON, and dict with len == 1 so we
            # don't break existing code already using find_and_modify.
            elif (isinstance(sort, ORDERED_TYPES) or
                  isinstance(sort, dict) and len(sort) == 1):
                warnings.warn("Passing mapping types for `sort` is deprecated,"
                              " use a list of (key, direction) pairs instead",
                              DeprecationWarning, stacklevel=2)
                kwargs['sort'] = sort
            else:
                raise TypeError("sort must be a list of (key, direction) "
                                "pairs, a dict of len 1, or an instance of "
                                "SON or OrderedDict")

        fields = kwargs.pop("fields", None)
        if fields is not None:
            kwargs["fields"] = helpers._fields_list_to_dict(fields, "fields")

        collation = validate_collation_or_none(kwargs.pop('collation', None))

        cmd = SON([("findAndModify", self.__name)])
        cmd.update(kwargs)

        write_concern = self._write_concern_for_cmd(cmd, None)

        def _find_and_modify(session, sock_info, retryable_write):
            if (sock_info.max_wire_version >= 4 and
                    not write_concern.is_server_default):
                cmd['writeConcern'] = write_concern.document
            result = self._command(
                sock_info, cmd, read_preference=ReadPreference.PRIMARY,
                allowable_errors=[_NO_OBJ_ERROR], collation=collation,
                session=session, retryable_write=retryable_write,
                user_fields=_FIND_AND_MODIFY_DOC_FIELDS)

            _check_write_command_response(result)
            return result

        out = self.__database.client._retryable_write(
            write_concern.acknowledged, _find_and_modify, None)

        if not out['ok']:
            if out["errmsg"] == _NO_OBJ_ERROR:
                return None
            else:
                # Should never get here b/c of allowable_errors
                raise ValueError("Unexpected Error: %s" % (out,))

        if full_response:
            return out
        else:
            document = out.get('value')
            if manipulate:
                document = self.__database._fix_outgoing(document, self)
            return document
975924
def _update(self, sock_info, criteria, document, upsert=False,
                check_keys=True, multi=False, manipulate=False,
                write_concern=None, op_id=None, ordered=True,
                bypass_doc_val=False, collation=None, array_filters=None,
                session=None, retryable_write=False):
        """"""
        common.validate_boolean("upsert", upsert)
        if manipulate:
            document = self.__database._fix_incoming(document, self)
        collation = validate_collation_or_none(collation)
        write_concern = write_concern or self.write_concern
        acknowledged = write_concern.acknowledged
        update_doc = SON([('q', criteria),
                          ('u', document),
                          ('multi', multi),
                          ('upsert', upsert)])
        if collation is not None:
            if sock_info.max_wire_version < 5:
                raise ConfigurationError(
                    'Must be connected to MongoDB 3.4+ to use collations.')
            elif not acknowledged:
                raise ConfigurationError(
                    'Collation is unsupported for unacknowledged writes.')
            else:
                update_doc['collation'] = collation
        if array_filters is not None:
            if sock_info.max_wire_version < 6:
                raise ConfigurationError(
                    'Must be connected to MongoDB 3.6+ to use array_filters.')
            elif not acknowledged:
                raise ConfigurationError(
                    'arrayFilters is unsupported for unacknowledged writes.')
            else:
                update_doc['arrayFilters'] = array_filters
        command = SON([('update', self.name),
                       ('ordered', ordered),
                       ('updates', [update_doc])])
        if not write_concern.is_server_default:
            command['writeConcern'] = write_concern.document

        if not sock_info.op_msg_enabled and not acknowledged:
            # Legacy OP_UPDATE.
            return self._legacy_write(
                sock_info, 'update', command, op_id,
                bypass_doc_val, message.update, self.__full_name, upsert,
                multi, criteria, document, False, write_concern.document,
                check_keys, self.__write_response_codec_options)

        # Update command.
        if bypass_doc_val and sock_info.max_wire_version >= 4:
            command['bypassDocumentValidation'] = True

        # The command result has to be published for APM unmodified
        # so we make a shallow copy here before adding updatedExisting.
        result = sock_info.command(
            self.__database.name,
            command,
            write_concern=write_concern,
            codec_options=self.__write_response_codec_options,
            session=session,
            client=self.__database.client,
            retryable_write=retryable_write).copy()
        _check_write_command_response(result)
        # Add the updatedExisting field for compatibility.
        if result.get('n') and 'upserted' not in result:
            result['updatedExisting'] = True
        else:
            result['updatedExisting'] = False
            # MongoDB >= 2.6.0 returns the upsert _id in an array
            # element. Break it out for backward compatibility.
            if 'upserted' in result:
                result['upserted'] = result['upserted'][0]['_id']

        if not acknowledged:
            return None
        return result
1212452
def replace(index, middleware, *args, &block)
      if index.is_a?(Integer)
        delete(index)
        insert(index, middleware, *args, &block)
      else
        insert_before(index, middleware, *args, &block)
        delete(index)
      end
    end
112301
def __find_and_modify(self, filter, projection, sort, upsert=None,
                          return_document=ReturnDocument.BEFORE,
                          array_filters=None, session=None, **kwargs):
        """"""

        common.validate_is_mapping("filter", filter)
        if not isinstance(return_document, bool):
            raise ValueError("return_document must be "
                             "ReturnDocument.BEFORE or ReturnDocument.AFTER")
        collation = validate_collation_or_none(kwargs.pop('collation', None))
        cmd = SON([("findAndModify", self.__name),
                   ("query", filter),
                   ("new", return_document)])
        cmd.update(kwargs)
        if projection is not None:
            cmd["fields"] = helpers._fields_list_to_dict(projection,
                                                         "projection")
        if sort is not None:
            cmd["sort"] = helpers._index_document(sort)
        if upsert is not None:
            common.validate_boolean("upsert", upsert)
            cmd["upsert"] = upsert

        write_concern = self._write_concern_for_cmd(cmd, session)

        def _find_and_modify(session, sock_info, retryable_write):
            if array_filters is not None:
                if sock_info.max_wire_version < 6:
                    raise ConfigurationError(
                        'Must be connected to MongoDB 3.6+ to use '
                        'arrayFilters.')
                if not write_concern.acknowledged:
                    raise ConfigurationError(
                        'arrayFilters is unsupported for unacknowledged '
                        'writes.')
                cmd["arrayFilters"] = array_filters
            if (sock_info.max_wire_version >= 4 and
                    not write_concern.is_server_default):
                cmd['writeConcern'] = write_concern.document
            out = self._command(sock_info, cmd,
                                read_preference=ReadPreference.PRIMARY,
                                write_concern=write_concern,
                                allowable_errors=[_NO_OBJ_ERROR],
                                collation=collation, session=session,
                                retryable_write=retryable_write,
                                user_fields=_FIND_AND_MODIFY_DOC_FIELDS)
            _check_write_command_response(out)

            return out.get("value")

        return self.__database.client._retryable_write(
            write_concern.acknowledged, _find_and_modify, session)
851855
def update(self, document_id, update_spec, namespace, timestamp):
        
        document = self.doc_dict[document_id].doc
        updated = self.apply_update(document, update_spec)
        if "_id" in updated:
            updated.pop("_id")
        updated[self.unique_key] = document_id
        self.upsert(updated, namespace, timestamp)
        return updated
694004
def update(self, **kwargs):
        
        if self.is_valid:
            if '_id' in self._document:
                to_update = self.find_one({'_id': self._id})

                if to_update:
                    before = self.before_update(old=to_update)
                    if before:
                        return before

                    try:
                        self.replace_one({'_id': self._id}, self._document)

                        self.after_update(old=to_update)

                        return self._document
                    except PyMongoException as exc:
                        return PyMongoError(
                            error_message=exc.details.get(
                                'errmsg', exc.details.get(
                                    'err', 'PyMongoError.'
                                )
                            ),
                            operation='update', collection=type(self).__name__,
                            document=self._document,
                        )
                else:
                    return DocumentNotFoundError(type(self).__name__, self._id)
            else:
                return UnidentifiedDocumentError(
                    type(self).__name__, self._document
                )

        return self._errors
574596
def replace data_hash = {}
    sql, *binds = SQLHelper.replace :table => name,
                                    :data => @query_default.merge(data_hash),
                                    :prepared => true
    pstmt = prepare :insert, sql
    pstmt.send @update_method, *binds
  end
796496
def replace(self):
        
        doc_dict = self.doc_dict.copy()
        for k, v in doc_dict.items():
            if '{' and '}' in v:
                self.doc_dict[k] = v.format(**doc_dict)
493711
def delete_documents(self):
    
    pk = str(self._primary_key)
    for doc in self._whoosh.searcher().documents():
      if pk in doc:
        doc_pk = str(doc[pk])
        self._whoosh.delete_by_term(pk, doc_pk)
1257486
def remove(self, document_id, namespace, timestamp):
        
        try:
            entry = self.doc_dict[document_id]
            entry.doc = None
            entry.update(namespace, timestamp)
        except KeyError:
            raise OperationFailed("Document does not exist: %s" % document_id)
136326
def repair_duplicate_names(self):
		
		for name in self._all_names():
			cur = self.db.find({'names': name})
			main_doc = next(cur)
			for duplicate in cur:
				query = {'_id': main_doc['_id']}
				update = {
					'$inc': {'value': duplicate['value']},
					'$push': {'names': {'$each': duplicate['names']}},
				}
				self.db.update(query, update)
				self.db.remove(duplicate)
396227
def update(self, document):
        
        if '_id' not in document:
            return self.insert(document)

        # Update the stored document, removing the id
        copy = document.copy()
        del copy['_id']

        self.db.execute("""
            update %s set data = ? where id = ?
        """ % self.name, (json.dumps(copy), document['_id']))

        return document
300402
def fetch_search_document(self, *, index):
        """"""
        assert self.pk, "Object must have a primary key before being indexed."
        client = get_client()
        return client.get(index=index, doc_type=self.search_doc_type, id=self.pk)