Search in sources :

Example 6 with DeleteResult

use of com.mongodb.client.result.DeleteResult in project nifi by apache.

the class DeleteMongo method onTrigger.

@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();
    final WriteConcern writeConcern = getWriteConcern(context);
    final MongoCollection<Document> collection = getCollection(context).withWriteConcern(writeConcern);
    final String deleteMode = context.getProperty(DELETE_MODE).getValue();
    final String deleteAttr = flowFile.getAttribute("mongodb.delete.mode");
    final Boolean failMode = context.getProperty(FAIL_ON_NO_DELETE).asBoolean();
    if (deleteMode.equals(DELETE_ATTR.getValue()) && (StringUtils.isEmpty(deleteAttr) || !ALLOWED_DELETE_VALUES.contains(deleteAttr.toLowerCase()))) {
        getLogger().error(String.format("%s is not an allowed value for mongodb.delete.mode", deleteAttr));
        session.transfer(flowFile, REL_FAILURE);
        return;
    }
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        session.exportTo(flowFile, bos);
        bos.close();
        String json = new String(bos.toByteArray());
        Document query = Document.parse(json);
        DeleteResult result;
        if (deleteMode.equals(DELETE_ONE.getValue()) || (deleteMode.equals(DELETE_ATTR.getValue()) && deleteAttr.toLowerCase().equals("one"))) {
            result = collection.deleteOne(query);
        } else {
            result = collection.deleteMany(query);
        }
        if (failMode && result.getDeletedCount() == 0) {
            session.transfer(flowFile, REL_FAILURE);
        } else {
            session.transfer(flowFile, REL_SUCCESS);
        }
    } catch (Exception ex) {
        getLogger().error("Could not send a delete to MongoDB, failing...", ex);
        session.transfer(flowFile, REL_FAILURE);
    }
}
Also used : FlowFile(org.apache.nifi.flowfile.FlowFile) WriteConcern(com.mongodb.WriteConcern) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(org.bson.Document) DeleteResult(com.mongodb.client.result.DeleteResult) ProcessException(org.apache.nifi.processor.exception.ProcessException)

Example 7 with DeleteResult

use of com.mongodb.client.result.DeleteResult in project sling by apache.

the class MongoDBNoSqlAdapter method deleteRecursive.

@Override
public boolean deleteRecursive(String path) {
    Pattern descendantsAndSelf = Pattern.compile("^" + Pattern.quote(path) + "(/.+)?$");
    DeleteResult result = collection.deleteMany(Filters.regex(PN_PATH, descendantsAndSelf));
    // return true if any document was deleted
    return result.getDeletedCount() > 0;
}
Also used : Pattern(java.util.regex.Pattern) DeleteResult(com.mongodb.client.result.DeleteResult)

Example 8 with DeleteResult

use of com.mongodb.client.result.DeleteResult in project spring-data-mongodb by spring-projects.

the class MongoTemplate method doRemove.

protected <T> DeleteResult doRemove(final String collectionName, final Query query, @Nullable final Class<T> entityClass) {
    Assert.notNull(query, "Query must not be null!");
    Assert.hasText(collectionName, "Collection name must not be null or empty!");
    final MongoPersistentEntity<?> entity = getPersistentEntity(entityClass);
    final Document queryObject = queryMapper.getMappedObject(query.getQueryObject(), entity);
    return execute(collectionName, new CollectionCallback<DeleteResult>() {

        public DeleteResult doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
            maybeEmitEvent(new BeforeDeleteEvent<T>(queryObject, entityClass, collectionName));
            Document removeQuery = queryObject;
            DeleteOptions options = new DeleteOptions();
            query.getCollation().map(Collation::toMongoCollation).ifPresent(options::collation);
            MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.REMOVE, collectionName, entityClass, null, queryObject);
            WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
            DeleteResult dr = null;
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Remove using query: {} in collection: {}.", new Object[] { serializeToJsonSafely(removeQuery), collectionName });
            }
            if (query.getLimit() > 0 || query.getSkip() > 0) {
                MongoCursor<Document> cursor = new QueryCursorPreparer(query, entityClass).prepare(collection.find(removeQuery).projection(new Document(ID_FIELD, 1))).iterator();
                Set<Object> ids = new LinkedHashSet<>();
                while (cursor.hasNext()) {
                    ids.add(cursor.next().get(ID_FIELD));
                }
                removeQuery = new Document(ID_FIELD, new Document("$in", ids));
            }
            if (writeConcernToUse == null) {
                dr = collection.deleteMany(removeQuery, options);
            } else {
                dr = collection.withWriteConcern(writeConcernToUse).deleteMany(removeQuery, options);
            }
            maybeEmitEvent(new AfterDeleteEvent<T>(queryObject, entityClass, collectionName));
            return dr;
        }
    });
}
Also used : MongoException(com.mongodb.MongoException) Document(org.bson.Document) BeforeDeleteEvent(org.springframework.data.mongodb.core.mapping.event.BeforeDeleteEvent) Collation(org.springframework.data.mongodb.core.query.Collation) AfterDeleteEvent(org.springframework.data.mongodb.core.mapping.event.AfterDeleteEvent) WriteConcern(com.mongodb.WriteConcern) MongoCursor(com.mongodb.client.MongoCursor) DeleteResult(com.mongodb.client.result.DeleteResult) DataAccessException(org.springframework.dao.DataAccessException)

Example 9 with DeleteResult

use of com.mongodb.client.result.DeleteResult in project MtgDesktopCompanion by nicho92.

the class MongoDbDAO method deleteAlert.

@Override
public void deleteAlert(MagicCardAlert alert) throws SQLException {
    logger.debug("delete alert " + alert);
    Bson filter = new Document("alertItem.id", alert.getId());
    DeleteResult res = db.getCollection(colAlerts).deleteOne(filter);
    logger.debug(res);
}
Also used : Document(org.bson.Document) DeleteResult(com.mongodb.client.result.DeleteResult) Bson(org.bson.conversions.Bson)

Example 10 with DeleteResult

use of com.mongodb.client.result.DeleteResult in project core-ng-project by neowu.

the class MongoCollectionImpl method delete.

@Override
public boolean delete(Object id) {
    StopWatch watch = new StopWatch();
    long deletedRows = 0;
    try {
        DeleteResult result = collection().deleteOne(Filters.eq("_id", id));
        deletedRows = result.getDeletedCount();
        return deletedRows == 1;
    } finally {
        long elapsedTime = watch.elapsedTime();
        ActionLogContext.track("mongoDB", elapsedTime, 0, (int) deletedRows);
        logger.debug("delete, collection={}, id={}, elapsedTime={}", collectionName, id, elapsedTime);
        checkSlowOperation(elapsedTime);
    }
}
Also used : DeleteResult(com.mongodb.client.result.DeleteResult) StopWatch(core.framework.util.StopWatch)

Aggregations

DeleteResult (com.mongodb.client.result.DeleteResult)46 Document (org.bson.Document)20 UpdateResult (com.mongodb.client.result.UpdateResult)10 BsonDocument (org.bson.BsonDocument)9 Test (org.junit.jupiter.api.Test)9 BasicDBObject (com.mongodb.BasicDBObject)7 WriteConcern (com.mongodb.WriteConcern)6 Bson (org.bson.conversions.Bson)6 MongoException (com.mongodb.MongoException)5 ArrayList (java.util.ArrayList)5 DataAccessException (org.springframework.dao.DataAccessException)5 MongoGridFSException (com.mongodb.MongoGridFSException)4 MongoClient (com.mongodb.client.MongoClient)4 OptimisticLockingFailureException (org.springframework.dao.OptimisticLockingFailureException)4 ReadPreference (com.mongodb.ReadPreference)3 MongoDatabase (com.mongodb.client.MongoDatabase)3 InsertOneResult (com.mongodb.client.result.InsertOneResult)3 MongoClient (com.mongodb.reactivestreams.client.MongoClient)3 MongoDatabase (com.mongodb.reactivestreams.client.MongoDatabase)3 ObjectId (org.bson.types.ObjectId)3