Search in sources :

Example 1 with InsertRequest

use of com.mongodb.internal.bulk.InsertRequest 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 2 with InsertRequest

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

the class CollectionHelper method insertDocuments.

public void insertDocuments(final List<BsonDocument> documents, final WriteConcern writeConcern, final WriteBinding binding) {
    List<InsertRequest> insertRequests = new ArrayList<InsertRequest>(documents.size());
    for (BsonDocument document : documents) {
        insertRequests.add(new InsertRequest(document));
    }
    new InsertOperation(namespace, true, writeConcern, false, insertRequests).execute(binding);
}
Also used : BsonDocument(org.bson.BsonDocument) InsertOperation(com.mongodb.internal.operation.InsertOperation) InsertRequest(com.mongodb.internal.bulk.InsertRequest) ArrayList(java.util.ArrayList)

Example 3 with InsertRequest

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

the class Operations method insertMany.

public MixedBulkWriteOperation insertMany(final List<? extends TDocument> documents, final InsertManyOptions options) {
    notNull("documents", documents);
    List<InsertRequest> requests = new ArrayList<>(documents.size());
    for (TDocument document : documents) {
        if (document == null) {
            throw new IllegalArgumentException("documents can not contain a null value");
        }
        if (getCodec() instanceof CollectibleCodec) {
            document = ((CollectibleCodec<TDocument>) getCodec()).generateIdIfAbsentFromDocument(document);
        }
        requests.add(new InsertRequest(documentToBsonDocument(document)));
    }
    return new MixedBulkWriteOperation(namespace, requests, options.isOrdered(), writeConcern, retryWrites).bypassDocumentValidation(options.getBypassDocumentValidation());
}
Also used : CollectibleCodec(org.bson.codecs.CollectibleCodec) InsertRequest(com.mongodb.internal.bulk.InsertRequest) ArrayList(java.util.ArrayList)

Example 4 with InsertRequest

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

the class MaxDocumentSizeTest method setUp.

@Before
public void setUp() {
    message = new InsertMessage("test.test", new InsertRequest(new BsonDocument("bytes", new BsonBinary(new byte[2048]))), MessageSettings.builder().maxDocumentSize(1024).build());
    buffer = new ByteBufferBsonOutput(new SimpleBufferProvider());
}
Also used : BsonDocument(org.bson.BsonDocument) BsonBinary(org.bson.BsonBinary) InsertRequest(com.mongodb.internal.bulk.InsertRequest) Before(org.junit.Before)

Example 5 with InsertRequest

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

the class DBCollection method insert.

/**
 * <p>Insert documents into a collection. If the collection does not exists on the server, then it will be created. If the new document
 * does not contain an '_id' field, it will be added.</p>
 *
 * <p>If the value of the continueOnError property of the given {@code InsertOptions} is true,
 * that value will override the value of the continueOnError property of the given {@code WriteConcern}. Otherwise,
 * the value of the continueOnError property of the given {@code WriteConcern} will take effect. </p>
 *
 * @param documents     a list of {@code DBObject}'s to be inserted
 * @param insertOptions the options to use for the insert
 * @return the result of the operation
 * @throws com.mongodb.DuplicateKeyException if the write failed to a duplicate unique key
 * @throws com.mongodb.WriteConcernException if the write failed due some other failure specific to the insert 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/insert-documents/ Insert Documents
 */
public WriteResult insert(final List<? extends DBObject> documents, final InsertOptions insertOptions) {
    WriteConcern writeConcern = insertOptions.getWriteConcern() != null ? insertOptions.getWriteConcern() : getWriteConcern();
    Encoder<DBObject> encoder = toEncoder(insertOptions.getDbEncoder());
    List<InsertRequest> insertRequestList = new ArrayList<InsertRequest>(documents.size());
    for (DBObject cur : documents) {
        if (cur.get(ID_FIELD_NAME) == null) {
            cur.put(ID_FIELD_NAME, new ObjectId());
        }
        insertRequestList.add(new InsertRequest(new BsonDocumentWrapper<DBObject>(cur, encoder)));
    }
    return insert(insertRequestList, writeConcern, insertOptions.isContinueOnError(), insertOptions.getBypassDocumentValidation());
}
Also used : ObjectId(org.bson.types.ObjectId) InsertRequest(com.mongodb.internal.bulk.InsertRequest) ArrayList(java.util.ArrayList) BsonDocumentWrapper(org.bson.BsonDocumentWrapper)

Aggregations

InsertRequest (com.mongodb.internal.bulk.InsertRequest)6 ArrayList (java.util.ArrayList)4 BsonDocument (org.bson.BsonDocument)3 DeleteRequest (com.mongodb.internal.bulk.DeleteRequest)2 UpdateRequest (com.mongodb.internal.bulk.UpdateRequest)2 WriteRequest (com.mongodb.internal.bulk.WriteRequest)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 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