Example usage for com.mongodb.client MongoCollection deleteMany

List of usage examples for com.mongodb.client MongoCollection deleteMany

Introduction

In this page you can find the example usage for com.mongodb.client MongoCollection deleteMany.

Prototype

DeleteResult deleteMany(Bson filter);

Source Link

Document

Removes all documents from the collection that match the given query filter.

Usage

From source file:com.bluedragon.mongo.MongoCollectionRemove.java

License:Open Source License

public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {
    MongoDatabase db = getMongoDatabase(_session, argStruct);

    String collection = getNamedStringParam(argStruct, "collection", null);
    if (collection == null)
        throwException(_session, "please specify a collection");

    cfData query = getNamedParam(argStruct, "query", null);
    if (query == null)
        throwException(_session, "please specify query to remove");

    try {//w  w w . j  ava 2  s .co m

        MongoCollection<Document> col = db.getCollection(collection);
        col.deleteMany(getDocument(query));
        return cfBooleanData.TRUE;

    } catch (MongoException me) {
        throwException(_session, me.getMessage());
        return null;
    }
}

From source file:com.eclipsesource.connect.persistence.MongoStorage.java

License:Open Source License

@Override
public void delete(Query<?> query) {
    checkArgument(query != null, "Query must not be null");
    MongoDatabase db = factory.getDB();//from  w w  w.ja va2s . c o  m
    MongoCollection<Document> collection = db.getCollection(query.getPlace());
    Document document = createDocument(query);
    collection.deleteMany(document);
}

From source file:com.eclipsesource.connect.test.util.persistence.InMemoryStorage.java

License:Open Source License

@Override
public void delete(Query<?> query) {
    checkArgument(query != null, "Query must not be null");
    MongoCollection<Document> collection = db.getCollection(query.getPlace());
    Document document = createDocument(query);
    collection.deleteMany(document);
}

From source file:com.eightkdata.mongowp.client.wrapper.MongoConnectionWrapper.java

License:Open Source License

@Override
public void asyncDelete(String database, String collection, boolean singleRemove, BsonDocument selector)
        throws MongoException {
    try {//from w  w  w.j  a v  a 2 s. co m
        MongoCollection<BsonDocument> collectionObject = owner.getDriverClient().getDatabase(database)
                .getCollection(collection, BsonDocument.class);
        org.bson.BsonDocument mongoSelector = MongoBsonTranslator.translate(selector);
        if (singleRemove) {
            collectionObject.deleteOne(mongoSelector);
        } else {
            collectionObject.deleteMany(mongoSelector);
        }
    } catch (com.mongodb.MongoException ex) { //a general Mongo driver exception
        if (ErrorCode.isErrorCode(ex.getCode())) {
            throw toMongoException(ex);
        } else {
            throw toRuntimeMongoException(ex);
        }
    } catch (IOException ex) {
        throw new BadValueException("Unexpected IO exception", ex);
    }
}

From source file:com.epam.dlab.mongo.DlabResourceTypeDAO.java

License:Apache License

/**
 * Update monthly total in Mongo DB./*from w w w .  j a v  a 2s  .c o  m*/
 *
 * @param month the month in format YYYY-MM.
 * @throws InitializationException
 */
public void updateMonthTotalCost(String month) throws InitializationException {
    LOGGER.debug("Update total cost for month {}", month);
    try {
        //Check month
        SimpleDateFormat fd = new SimpleDateFormat("yyyy-MM");
        fd.parse(month);
    } catch (java.text.ParseException e) {
        throw new InitializationException("Invalid month value. " + e.getLocalizedMessage(), e);
    }

    List<? extends Bson> pipeline = Arrays.asList(
            match(and(gte(ReportLine.FIELD_USAGE_DATE, month + "-01"),
                    lte(ReportLine.FIELD_USAGE_DATE, month + "-31"))),
            group(getGrouppingFields(FIELD_DLAB_RESOURCE_ID, FIELD_DLAB_RESOURCE_TYPE, FIELD_USER,
                    FIELD_EXPLORATORY_NAME, ReportLine.FIELD_CURRENCY_CODE, ReportLine.FIELD_RESOURCE_TYPE),
                    sum(ReportLine.FIELD_COST, "$" + ReportLine.FIELD_COST)));
    AggregateIterable<Document> docs = connection.getCollection(COLLECTION_BILLING).aggregate(pipeline);

    MongoCollection<Document> collection = connection.getCollection(COLLECTION_BILLING_TOTAL);
    long deletedCount = collection.deleteMany(eq(ReportLine.FIELD_USAGE_DATE, month)).getDeletedCount();
    LOGGER.debug("{} documents has been deleted from collection {}", deletedCount, COLLECTION_BILLING_TOTAL);
    List<Document> totals = new ArrayList<>();
    for (Document d : docs) {
        Document total = (Document) d.get(FIELD_ID);
        total.append(ReportLine.FIELD_USAGE_DATE, month).append(ReportLine.FIELD_COST,
                d.getDouble(ReportLine.FIELD_COST));
        totals.add(total);
    }
    if (!totals.isEmpty()) {
        LOGGER.debug("{} documents will be inserted into collection {}", totals.size(),
                COLLECTION_BILLING_TOTAL);
        collection.insertMany(totals);
    }
}

From source file:com.epam.dlab.mongo.MongoDbConnection.java

License:Apache License

/**
 * Delete the documents from Mongo collection.
 *
 * @param collection    Mongo collection.
 * @param usageDateList list of the data interval to deletion data from Mongo.
 * @throws AdapterException/*from   www. ja  v a  2 s. co  m*/
 */
public void deleteRows(MongoCollection<Document> collection, UsageDataList usageDateList)
        throws AdapterException {
    try {
        long rowCount = 0;
        for (String date : usageDateList) {
            if (!usageDateList.get(date)) {
                DeleteResult result = collection.deleteMany(eq(ReportLine.FIELD_USAGE_DATE, date));
                rowCount += result.getDeletedCount();
                usageDateList.set(date, true);
            }
        }
        if (rowCount > 0) {
            LOGGER.debug("{} documents has been deleted from collection {}", rowCount,
                    collection.getNamespace());
        }
    } catch (Exception e) {
        throw new AdapterException("Cannot delete old rows from collection " + collection.getNamespace() + ": "
                + e.getLocalizedMessage(), e);
    }
}

From source file:com.left8.evs.utilities.dsretriever.MongoHandler.java

License:Open Source License

/**
 * Removes all retweets that are found in the MongoDB Store for which their
 * original tweet is also stored in the DB.<br>
 * More formally, it parses all stored tweets and checks whether a specific
 * tweet is also a retweet. When this condition is true, the method tries to
 * find whether the tweet that this retweet is originated from, also exists
 * in the store and if so, the retweet is removed from the collection.
 * <br>/*from  ww w . j  a v  a 2  s  .  c o  m*/
 * *WARNING:* This process is "one-way", meaning that once initiated the 
 * retweets that are going to be removed cannot be restored back.
 */
public void removeRetweets() {
    Utilities.printMessageln("Starting process of removing...");
    List<Tweet> tweets = retrieveAllTweetsFiltered();
    if (tweets.isEmpty()) {
        Utilities.printMessageln("There are no tweets stored in the database.");
        return;
    }
    MongoCollection<Document> collection = db.getCollection(config.getRawTweetsCollectionName());
    List<Tweet> tweetsToBeRemoved = new ArrayList<>();

    Utilities.printMessageln("Gathering retweets...");

    //Find the retweets
    for (int i = 0; i < tweets.size(); i++) {
        Tweet tweet = tweets.get(i);

        //If the tweet is a retweet and the source of it exists, remove it
        if (tweet.isRetweet() && tweetExists(tweet.getOriginalIDOfRetweet())) {
            tweetsToBeRemoved.add(tweet);
            tweets.remove(tweet);
        }
    }

    Utilities.printMessageln("Removing retweets from MongoDB Store...");
    for (Tweet tweet : tweetsToBeRemoved) {
        collection.deleteMany(new Document(config.getTweetIdFieldName(), tweet.getID()));
    }

    Utilities.printMessageln("Retweets were successfully removed.");
    Utilities.printMessageln("Total size of removed retweets: " + tweetsToBeRemoved.size());
    Utilities.printMessageln("Size of stored tweets after deletion: " + tweets.size());
}

From source file:com.navercorp.pinpoint.plugin.mongodb.MongoDBBase.java

License:Apache License

public void deleteData(PluginTestVerifier verifier, MongoCollection<Document> collection,
        Class<?> mongoDatabaseImpl) {
    //delete data
    Document doc = new Document("name", "Roy3");
    Object[] objects = new Object[1];
    objects[0] = doc;/* www .j  a  v a2s  .c  o m*/

    StringStringValue parsedBson = MongoUtil.parseBson(objects, true);

    DeleteResult deleteResult = collection.deleteMany(doc);

    Method deleteMany;
    try {
        deleteMany = mongoDatabaseImpl.getDeclaredMethod("deleteMany", Bson.class);
    } catch (NoSuchMethodException e) {
        deleteMany = null;
    }

    verifier.verifyTrace(event(MONGO_EXECUTE_QUERY, deleteMany, null, MONGODB_ADDRESS, null,
            new ExpectedAnnotation(MongoConstants.MONGO_COLLECTION_INFO.getName(), "customers"),
            new ExpectedAnnotation(MongoConstants.MONGO_COLLECTION_OPTION.getName(), "MAJORITY"),
            new ExpectedAnnotation(MongoConstants.MONGO_JSON_DATA.getName(), parsedBson)));

    Assert.assertEquals(1, deleteResult.getDeletedCount());
}

From source file:com.redhat.thermostat.gateway.common.mongodb.executor.MongoExecutor.java

License:Open Source License

public MongoDataResultContainer execDeleteRequest(MongoCollection<Document> collection, List<String> queries,
        Set<String> realms) {
    MongoDataResultContainer metaDataContainer = new MongoDataResultContainer();
    if (queries != null && !queries.isEmpty() || realms != null && !realms.isEmpty()) {
        Bson bsonQueries = MongoRequestFilters.buildQuery(queries, realms);
        metaDataContainer.setDeleteReqMatches(collection.count(bsonQueries));
        collection.deleteMany(bsonQueries);
    } else {/*from   w w  w .j  a  va 2  s.co  m*/
        metaDataContainer.setDeleteReqMatches(collection.count());
        collection.drop();
    }

    return metaDataContainer;
}

From source file:com.redhat.thermostat.gateway.common.mongodb.MongoStorageHandler.java

License:Open Source License

public void deleteMany(MongoCollection<Document> collection, Bson query) {
    collection.deleteMany(query);
}