Search in sources :

Example 1 with DeleteRequest

use of com.mongodb.internal.bulk.DeleteRequest in project mongo-java-driver by mongodb.

the class DBCollection method remove.

/**
 * Remove documents from a collection.
 *
 * @param query   the deletion criteria using query operators. Omit the query parameter or pass an empty document to delete all
 *                documents in the collection.
 * @param options the options to apply to the delete operation
 * @return the result of the operation
 * @throws com.mongodb.WriteConcernException if the write failed due some other failure specific to the delete command
 * @throws com.mongodb.MongoCommandException if the write failed due to a specific command exception
 * @throws MongoException if the operation failed for some other reason
 * @mongodb.driver.manual tutorial/remove-documents/ Remove Documents
 * @since 3.4
 */
public WriteResult remove(final DBObject query, final DBCollectionRemoveOptions options) {
    notNull("query", query);
    notNull("options", options);
    WriteConcern writeConcern = options.getWriteConcern() != null ? options.getWriteConcern() : getWriteConcern();
    DeleteRequest deleteRequest = new DeleteRequest(wrap(query, options.getEncoder())).collation(options.getCollation());
    return executeWriteOperation(new DeleteOperation(getNamespace(), false, writeConcern, retryWrites, singletonList(deleteRequest)));
}
Also used : FindAndDeleteOperation(com.mongodb.internal.operation.FindAndDeleteOperation) DeleteOperation(com.mongodb.internal.operation.DeleteOperation) DeleteRequest(com.mongodb.internal.bulk.DeleteRequest)

Example 2 with DeleteRequest

use of com.mongodb.internal.bulk.DeleteRequest in project mongo-java-driver by mongodb.

the class MixedBulkWriteOperation method executeLegacyBatchesAsync.

private void executeLegacyBatchesAsync(final AsyncWriteBinding binding, final AsyncConnection connection, final SingleResultCallback<BulkWriteResult> callback) {
    List<? extends WriteRequest> writeRequests = getWriteRequests();
    LoopState loopState = new LoopState();
    AsyncCallbackRunnable loop = new AsyncCallbackLoop(loopState, iterationCallback -> {
        int i = loopState.iteration();
        if (loopState.breakAndCompleteIf(() -> i == writeRequests.size(), iterationCallback)) {
            return;
        }
        WriteRequest writeRequest = writeRequests.get(i);
        SingleResultCallback<WriteConcernResult> commandCallback = (ignored, t) -> iterationCallback.onResult(null, t);
        if (writeRequest.getType() == INSERT) {
            connection.insertAsync(getNamespace(), isOrdered(), (InsertRequest) writeRequest, binding.getRequestContext(), commandCallback);
        } else if (writeRequest.getType() == UPDATE || writeRequest.getType() == REPLACE) {
            connection.updateAsync(getNamespace(), isOrdered(), (UpdateRequest) writeRequest, binding.getRequestContext(), commandCallback);
        } else {
            connection.deleteAsync(getNamespace(), isOrdered(), (DeleteRequest) writeRequest, binding.getRequestContext(), commandCallback);
        }
    });
    loop.run((voidResult, t) -> {
        if (t != null) {
            callback.onResult(null, t);
        } else {
            callback.onResult(BulkWriteResult.unacknowledged(), null);
        }
    });
}
Also used : LoopState(com.mongodb.internal.async.function.LoopState) AsyncCallbackRunnable(com.mongodb.internal.async.function.AsyncCallbackRunnable) LoopState(com.mongodb.internal.async.function.LoopState) WriteRequest(com.mongodb.internal.bulk.WriteRequest) CommandOperationHelper.addRetryableWriteErrorLabel(com.mongodb.internal.operation.CommandOperationHelper.addRetryableWriteErrorLabel) MongoBulkWriteException(com.mongodb.MongoBulkWriteException) MongoWriteConcernWithResponseException(com.mongodb.internal.connection.MongoWriteConcernWithResponseException) ProtocolHelper(com.mongodb.internal.connection.ProtocolHelper) ConnectionDescription(com.mongodb.connection.ConnectionDescription) BsonArray(org.bson.BsonArray) OperationHelper.validateWriteRequests(com.mongodb.internal.operation.OperationHelper.validateWriteRequests) OperationHelper.withSourceAndConnection(com.mongodb.internal.operation.OperationHelper.withSourceAndConnection) MongoException(com.mongodb.MongoException) AsyncCallbackSupplier(com.mongodb.internal.async.function.AsyncCallbackSupplier) Set(java.util.Set) Collectors(java.util.stream.Collectors) AsyncCallbackRunnable(com.mongodb.internal.async.function.AsyncCallbackRunnable) ServerVersionHelper.serverIsAtLeastVersionThreeDotSix(com.mongodb.internal.operation.ServerVersionHelper.serverIsAtLeastVersionThreeDotSix) SingleResultCallback(com.mongodb.internal.async.SingleResultCallback) REPLACE(com.mongodb.internal.bulk.WriteRequest.Type.REPLACE) RetryState(com.mongodb.internal.async.function.RetryState) List(java.util.List) Assertions.notNull(com.mongodb.assertions.Assertions.notNull) Optional(java.util.Optional) RetryingSyncSupplier(com.mongodb.internal.async.function.RetryingSyncSupplier) InsertRequest(com.mongodb.internal.bulk.InsertRequest) RetryingAsyncCallbackSupplier(com.mongodb.internal.async.function.RetryingAsyncCallbackSupplier) CommandOperationHelper.logRetryExecute(com.mongodb.internal.operation.CommandOperationHelper.logRetryExecute) CommandOperationHelper.exceptionTransformingCallback(com.mongodb.internal.operation.CommandOperationHelper.exceptionTransformingCallback) ErrorHandlingResultCallback.errorHandlingCallback(com.mongodb.internal.async.ErrorHandlingResultCallback.errorHandlingCallback) BsonString(org.bson.BsonString) Supplier(java.util.function.Supplier) BsonDocument(org.bson.BsonDocument) LOGGER(com.mongodb.internal.operation.OperationHelper.LOGGER) Connection(com.mongodb.internal.connection.Connection) NoOpFieldNameValidator(com.mongodb.internal.validator.NoOpFieldNameValidator) WriteBinding(com.mongodb.internal.binding.WriteBinding) Assertions(com.mongodb.assertions.Assertions) WriteConcernResult(com.mongodb.WriteConcernResult) AsyncCallbackLoop(com.mongodb.internal.async.function.AsyncCallbackLoop) AsyncWriteBinding(com.mongodb.internal.binding.AsyncWriteBinding) DeleteRequest(com.mongodb.internal.bulk.DeleteRequest) SessionContext(com.mongodb.internal.session.SessionContext) FieldNameValidator(org.bson.FieldNameValidator) OperationHelper.validateWriteRequestsAndCompleteIfInvalid(com.mongodb.internal.operation.OperationHelper.validateWriteRequestsAndCompleteIfInvalid) INSERT(com.mongodb.internal.bulk.WriteRequest.Type.INSERT) MongoNamespace(com.mongodb.MongoNamespace) UpdateRequest(com.mongodb.internal.bulk.UpdateRequest) OperationHelper.isRetryableWrite(com.mongodb.internal.operation.OperationHelper.isRetryableWrite) CommandOperationHelper.transformWriteException(com.mongodb.internal.operation.CommandOperationHelper.transformWriteException) Assertions.isTrueArgument(com.mongodb.assertions.Assertions.isTrueArgument) Assertions.assertTrue(com.mongodb.assertions.Assertions.assertTrue) OperationHelper.withAsyncSourceAndConnection(com.mongodb.internal.operation.OperationHelper.withAsyncSourceAndConnection) BulkWriteResult(com.mongodb.bulk.BulkWriteResult) Nullable(com.mongodb.lang.Nullable) WriteConcern(com.mongodb.WriteConcern) UPDATE(com.mongodb.internal.bulk.WriteRequest.Type.UPDATE) AsyncConnection(com.mongodb.internal.connection.AsyncConnection) AttachmentKeys(com.mongodb.internal.operation.retry.AttachmentKeys) WriteConcernResult(com.mongodb.WriteConcernResult) UpdateRequest(com.mongodb.internal.bulk.UpdateRequest) WriteRequest(com.mongodb.internal.bulk.WriteRequest) AsyncCallbackLoop(com.mongodb.internal.async.function.AsyncCallbackLoop) DeleteRequest(com.mongodb.internal.bulk.DeleteRequest)

Example 3 with DeleteRequest

use of com.mongodb.internal.bulk.DeleteRequest in project mongo-java-driver by mongodb.

the class OperationHelper method validateWriteRequestCollations.

static void validateWriteRequestCollations(final ConnectionDescription connectionDescription, final List<? extends WriteRequest> requests, final WriteConcern writeConcern) {
    Collation collation = null;
    for (WriteRequest request : requests) {
        if (request instanceof UpdateRequest) {
            collation = ((UpdateRequest) request).getCollation();
        } else if (request instanceof DeleteRequest) {
            collation = ((DeleteRequest) request).getCollation();
        }
        if (collation != null) {
            break;
        }
    }
    validateCollationAndWriteConcern(connectionDescription, collation, writeConcern);
}
Also used : UpdateRequest(com.mongodb.internal.bulk.UpdateRequest) WriteRequest(com.mongodb.internal.bulk.WriteRequest) Collation(com.mongodb.client.model.Collation) DeleteRequest(com.mongodb.internal.bulk.DeleteRequest)

Example 4 with DeleteRequest

use of com.mongodb.internal.bulk.DeleteRequest in project mongo-java-driver by mongodb.

the class OperationHelper method validateWriteRequestHints.

static void validateWriteRequestHints(final ConnectionDescription connectionDescription, final List<? extends WriteRequest> requests, final WriteConcern writeConcern) {
    for (WriteRequest request : requests) {
        Bson hint = null;
        String hintString = null;
        if (request instanceof UpdateRequest) {
            hint = ((UpdateRequest) request).getHint();
            hintString = ((UpdateRequest) request).getHintString();
        } else if (request instanceof DeleteRequest) {
            hint = ((DeleteRequest) request).getHint();
            hintString = ((DeleteRequest) request).getHintString();
        }
        if (hint != null || hintString != null) {
            validateWriteRequestHint(connectionDescription, writeConcern, request);
            break;
        }
    }
}
Also used : UpdateRequest(com.mongodb.internal.bulk.UpdateRequest) WriteRequest(com.mongodb.internal.bulk.WriteRequest) DeleteRequest(com.mongodb.internal.bulk.DeleteRequest) Bson(org.bson.conversions.Bson)

Example 5 with DeleteRequest

use of com.mongodb.internal.bulk.DeleteRequest in project mongo-java-driver by mongodb.

the class Operations method bulkWrite.

@SuppressWarnings("unchecked")
public MixedBulkWriteOperation bulkWrite(final List<? extends WriteModel<? extends TDocument>> requests, final BulkWriteOptions options) {
    notNull("requests", requests);
    List<WriteRequest> writeRequests = new ArrayList<>(requests.size());
    for (WriteModel<? extends TDocument> writeModel : requests) {
        WriteRequest writeRequest;
        if (writeModel == null) {
            throw new IllegalArgumentException("requests can not contain a null value");
        } else if (writeModel instanceof InsertOneModel) {
            TDocument document = ((InsertOneModel<TDocument>) writeModel).getDocument();
            if (getCodec() instanceof CollectibleCodec) {
                document = ((CollectibleCodec<TDocument>) getCodec()).generateIdIfAbsentFromDocument(document);
            }
            writeRequest = new InsertRequest(documentToBsonDocument(document));
        } else if (writeModel instanceof ReplaceOneModel) {
            ReplaceOneModel<TDocument> replaceOneModel = (ReplaceOneModel<TDocument>) writeModel;
            writeRequest = new UpdateRequest(toBsonDocument(replaceOneModel.getFilter()), documentToBsonDocument(replaceOneModel.getReplacement()), WriteRequest.Type.REPLACE).upsert(replaceOneModel.getReplaceOptions().isUpsert()).collation(replaceOneModel.getReplaceOptions().getCollation()).hint(replaceOneModel.getReplaceOptions().getHint()).hintString(replaceOneModel.getReplaceOptions().getHintString());
        } else if (writeModel instanceof UpdateOneModel) {
            UpdateOneModel<TDocument> updateOneModel = (UpdateOneModel<TDocument>) writeModel;
            BsonValue update = updateOneModel.getUpdate() != null ? toBsonDocument(updateOneModel.getUpdate()) : new BsonArray(toBsonDocumentList(updateOneModel.getUpdatePipeline()));
            writeRequest = new UpdateRequest(toBsonDocument(updateOneModel.getFilter()), update, WriteRequest.Type.UPDATE).multi(false).upsert(updateOneModel.getOptions().isUpsert()).collation(updateOneModel.getOptions().getCollation()).arrayFilters(toBsonDocumentList(updateOneModel.getOptions().getArrayFilters())).hint(updateOneModel.getOptions().getHint()).hintString(updateOneModel.getOptions().getHintString());
        } else if (writeModel instanceof UpdateManyModel) {
            UpdateManyModel<TDocument> updateManyModel = (UpdateManyModel<TDocument>) writeModel;
            BsonValue update = updateManyModel.getUpdate() != null ? toBsonDocument(updateManyModel.getUpdate()) : new BsonArray(toBsonDocumentList(updateManyModel.getUpdatePipeline()));
            writeRequest = new UpdateRequest(toBsonDocument(updateManyModel.getFilter()), update, WriteRequest.Type.UPDATE).multi(true).upsert(updateManyModel.getOptions().isUpsert()).collation(updateManyModel.getOptions().getCollation()).arrayFilters(toBsonDocumentList(updateManyModel.getOptions().getArrayFilters())).hint(updateManyModel.getOptions().getHint()).hintString(updateManyModel.getOptions().getHintString());
        } else if (writeModel instanceof DeleteOneModel) {
            DeleteOneModel<TDocument> deleteOneModel = (DeleteOneModel<TDocument>) writeModel;
            writeRequest = new DeleteRequest(toBsonDocument(deleteOneModel.getFilter())).multi(false).collation(deleteOneModel.getOptions().getCollation()).hint(deleteOneModel.getOptions().getHint()).hintString(deleteOneModel.getOptions().getHintString());
        } else if (writeModel instanceof DeleteManyModel) {
            DeleteManyModel<TDocument> deleteManyModel = (DeleteManyModel<TDocument>) writeModel;
            writeRequest = new DeleteRequest(toBsonDocument(deleteManyModel.getFilter())).multi(true).collation(deleteManyModel.getOptions().getCollation()).hint(deleteManyModel.getOptions().getHint()).hintString(deleteManyModel.getOptions().getHintString());
        } else {
            throw new UnsupportedOperationException(format("WriteModel of type %s is not supported", writeModel.getClass()));
        }
        writeRequests.add(writeRequest);
    }
    return new MixedBulkWriteOperation(namespace, writeRequests, options.isOrdered(), writeConcern, retryWrites).bypassDocumentValidation(options.getBypassDocumentValidation());
}
Also used : InsertOneModel(com.mongodb.client.model.InsertOneModel) CollectibleCodec(org.bson.codecs.CollectibleCodec) UpdateRequest(com.mongodb.internal.bulk.UpdateRequest) WriteRequest(com.mongodb.internal.bulk.WriteRequest) InsertRequest(com.mongodb.internal.bulk.InsertRequest) ReplaceOneModel(com.mongodb.client.model.ReplaceOneModel) ArrayList(java.util.ArrayList) DeleteOneModel(com.mongodb.client.model.DeleteOneModel) UpdateOneModel(com.mongodb.client.model.UpdateOneModel) BsonArray(org.bson.BsonArray) UpdateManyModel(com.mongodb.client.model.UpdateManyModel) DeleteRequest(com.mongodb.internal.bulk.DeleteRequest) BsonValue(org.bson.BsonValue) DeleteManyModel(com.mongodb.client.model.DeleteManyModel)

Aggregations

DeleteRequest (com.mongodb.internal.bulk.DeleteRequest)5 UpdateRequest (com.mongodb.internal.bulk.UpdateRequest)4 WriteRequest (com.mongodb.internal.bulk.WriteRequest)4 InsertRequest (com.mongodb.internal.bulk.InsertRequest)2 MongoBulkWriteException (com.mongodb.MongoBulkWriteException)1 MongoException (com.mongodb.MongoException)1 MongoNamespace (com.mongodb.MongoNamespace)1 WriteConcern (com.mongodb.WriteConcern)1 WriteConcernResult (com.mongodb.WriteConcernResult)1 Assertions (com.mongodb.assertions.Assertions)1 Assertions.assertTrue (com.mongodb.assertions.Assertions.assertTrue)1 Assertions.isTrueArgument (com.mongodb.assertions.Assertions.isTrueArgument)1 Assertions.notNull (com.mongodb.assertions.Assertions.notNull)1 BulkWriteResult (com.mongodb.bulk.BulkWriteResult)1 Collation (com.mongodb.client.model.Collation)1 DeleteManyModel (com.mongodb.client.model.DeleteManyModel)1 DeleteOneModel (com.mongodb.client.model.DeleteOneModel)1 InsertOneModel (com.mongodb.client.model.InsertOneModel)1 ReplaceOneModel (com.mongodb.client.model.ReplaceOneModel)1 UpdateManyModel (com.mongodb.client.model.UpdateManyModel)1