Search in sources :

Example 1 with BulkWriteResult

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

the class MongoCollectionImpl method insertMany.

@Override
public void insertMany(final List<? extends TDocument> documents, final InsertManyOptions options, final SingleResultCallback<Void> callback) {
    notNull("documents", documents);
    List<InsertRequest> requests = new ArrayList<InsertRequest>(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)));
    }
    executor.execute(new MixedBulkWriteOperation(namespace, requests, options.isOrdered(), writeConcern).bypassDocumentValidation(options.getBypassDocumentValidation()), errorHandlingCallback(new SingleResultCallback<BulkWriteResult>() {

        @Override
        public void onResult(final BulkWriteResult result, final Throwable t) {
            callback.onResult(null, t);
        }
    }, LOGGER));
}
Also used : CollectibleCodec(org.bson.codecs.CollectibleCodec) InsertRequest(com.mongodb.bulk.InsertRequest) ArrayList(java.util.ArrayList) SingleResultCallback(com.mongodb.async.SingleResultCallback) BulkWriteResult(com.mongodb.bulk.BulkWriteResult) MixedBulkWriteOperation(com.mongodb.operation.MixedBulkWriteOperation)

Example 2 with BulkWriteResult

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

the class InsertCommandProtocol method execute.

@Override
public BulkWriteResult execute(final InternalConnection connection) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(format("Inserting %d documents into namespace %s on connection [%s] to server %s", insertRequests.size(), getNamespace(), connection.getDescription().getConnectionId(), connection.getDescription().getServerAddress()));
    }
    BulkWriteResult writeResult = super.execute(connection);
    LOGGER.debug("Insert completed");
    return writeResult;
}
Also used : BulkWriteResult(com.mongodb.bulk.BulkWriteResult)

Example 3 with BulkWriteResult

use of com.mongodb.bulk.BulkWriteResult in project jackrabbit-oak by apache.

the class MongoDocumentStore method sendBulkUpdate.

private <T extends Document> BulkUpdateResult sendBulkUpdate(Collection<T> collection, java.util.Collection<UpdateOp> updateOps, Map<String, T> oldDocs) {
    MongoCollection<BasicDBObject> dbCollection = getDBCollection(collection);
    List<WriteModel<BasicDBObject>> writes = new ArrayList<>(updateOps.size());
    String[] bulkIds = new String[updateOps.size()];
    int i = 0;
    for (UpdateOp updateOp : updateOps) {
        String id = updateOp.getId();
        Bson query = createQueryForUpdate(id, updateOp.getConditions());
        T oldDoc = oldDocs.get(id);
        if (oldDoc == null || oldDoc == NodeDocument.NULL) {
            query = Filters.and(query, Filters.exists(Document.MOD_COUNT, false));
            writes.add(new UpdateOneModel<>(query, createUpdate(updateOp, true), new UpdateOptions().upsert(true)));
        } else {
            query = Filters.and(query, Filters.eq(Document.MOD_COUNT, oldDoc.getModCount()));
            writes.add(new UpdateOneModel<>(query, createUpdate(updateOp, false), new UpdateOptions().upsert(true)));
        }
        bulkIds[i++] = id;
    }
    BulkWriteResult bulkResult;
    Set<String> failedUpdates = new HashSet<String>();
    Set<String> upserts = new HashSet<String>();
    try {
        bulkResult = dbCollection.bulkWrite(writes, new BulkWriteOptions().ordered(false));
    } catch (MongoBulkWriteException e) {
        bulkResult = e.getWriteResult();
        for (BulkWriteError err : e.getWriteErrors()) {
            failedUpdates.add(bulkIds[err.getIndex()]);
        }
    }
    for (BulkWriteUpsert upsert : bulkResult.getUpserts()) {
        upserts.add(bulkIds[upsert.getIndex()]);
    }
    return new BulkUpdateResult(failedUpdates, upserts);
}
Also used : BulkWriteUpsert(com.mongodb.bulk.BulkWriteUpsert) UpdateOp(org.apache.jackrabbit.oak.plugins.document.UpdateOp) ArrayList(java.util.ArrayList) BulkWriteError(com.mongodb.bulk.BulkWriteError) WriteModel(com.mongodb.client.model.WriteModel) UpdateOptions(com.mongodb.client.model.UpdateOptions) FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) BulkWriteResult(com.mongodb.bulk.BulkWriteResult) Bson(org.bson.conversions.Bson) BasicDBObject(com.mongodb.BasicDBObject) BulkWriteOptions(com.mongodb.client.model.BulkWriteOptions) MongoBulkWriteException(com.mongodb.MongoBulkWriteException) HashSet(java.util.HashSet)

Example 4 with BulkWriteResult

use of com.mongodb.bulk.BulkWriteResult in project core-ng-project by neowu.

the class MongoCollectionImpl method bulkDelete.

@Override
public long bulkDelete(List<?> ids) {
    StopWatch watch = new StopWatch();
    int deletedRows = 0;
    try {
        List<DeleteOneModel<T>> models = new ArrayList<>(ids.size());
        for (Object id : ids) {
            models.add(new DeleteOneModel<>(Filters.eq("_id", id)));
        }
        BulkWriteResult result = collection().bulkWrite(models, new BulkWriteOptions().ordered(false));
        deletedRows = result.getDeletedCount();
        return deletedRows;
    } finally {
        long elapsedTime = watch.elapsedTime();
        ActionLogContext.track("mongoDB", elapsedTime, 0, deletedRows);
        logger.debug("bulkDelete, collection={}, size={}, elapsedTime={}", collectionName, ids.size(), elapsedTime);
        checkSlowOperation(elapsedTime);
    }
}
Also used : BulkWriteOptions(com.mongodb.client.model.BulkWriteOptions) ArrayList(java.util.ArrayList) DeleteOneModel(com.mongodb.client.model.DeleteOneModel) BulkWriteResult(com.mongodb.bulk.BulkWriteResult) StopWatch(core.framework.util.StopWatch)

Example 5 with BulkWriteResult

use of com.mongodb.bulk.BulkWriteResult in project AtherysCore by Atherys-Horizons.

the class AbstractMongoDatabaseManager method saveAll.

@Override
public void saveAll(Collection<T> objects) {
    List<WriteModel<Document>> updates = new ArrayList<>();
    for (T object : objects) {
        Optional<Document> doc = toDocument(object);
        if (!doc.isPresent())
            continue;
        updates.add(new UpdateOneModel<>(new Document("uuid", object.getUUID()), new Document("$set", doc.get()), new UpdateOptions().upsert(true)));
    }
    if (!updates.isEmpty()) {
        BulkWriteResult bulkWriteResult = getCollection().bulkWrite(updates);
        if (bulkWriteResult.wasAcknowledged()) {
            int mods = bulkWriteResult.getModifiedCount();
            int inserts = bulkWriteResult.getInsertedCount();
            int deletes = bulkWriteResult.getDeletedCount();
            int matched = bulkWriteResult.getMatchedCount();
            logger.info("[MongoDB] " + this.getClass().getSimpleName() + " updated " + updates.size() + " objects, " + "where " + mods + " were modified, " + inserts + " were added, " + deletes + " were removed, and " + matched + " were matched.");
        }
    }
}
Also used : Document(org.bson.Document) WriteModel(com.mongodb.client.model.WriteModel) UpdateOptions(com.mongodb.client.model.UpdateOptions) BulkWriteResult(com.mongodb.bulk.BulkWriteResult)

Aggregations

BulkWriteResult (com.mongodb.bulk.BulkWriteResult)17 MongoException (com.mongodb.MongoException)5 BsonDocument (org.bson.BsonDocument)5 MongoBulkWriteException (com.mongodb.MongoBulkWriteException)4 Assertions (com.mongodb.assertions.Assertions)4 BulkWriteOptions (com.mongodb.client.model.BulkWriteOptions)4 WriteModel (com.mongodb.client.model.WriteModel)4 ArrayList (java.util.ArrayList)4 WriteConcern (com.mongodb.WriteConcern)3 ConnectionDescription (com.mongodb.connection.ConnectionDescription)3 AsyncCallbackLoop (com.mongodb.internal.async.function.AsyncCallbackLoop)3 AsyncCallbackRunnable (com.mongodb.internal.async.function.AsyncCallbackRunnable)3 LoopState (com.mongodb.internal.async.function.LoopState)3 RetryState (com.mongodb.internal.async.function.RetryState)3 List (java.util.List)3 Optional (java.util.Optional)3 Collectors (java.util.stream.Collectors)3 BsonString (org.bson.BsonString)3 Document (org.bson.Document)3 MongoNamespace (com.mongodb.MongoNamespace)2