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:henu.dao.impl.CaclDaoImpl.java

License:Open Source License

@Override
public boolean alterUserDate(String cid, String uid, String data) {
    MongoCollection<Document> collection = NosqlDB.getCollection(cid);
    data = data.replace("\'", "\"");
    Bson json = Document.parse(data);

    collection.deleteMany(Filters.eq("uid", uid));
    collection.insertOne((Document) json);
    //collection.updateMany(Filters.eq("uid", uid), json);
    return true;//from   ww w  . j  a v a2 s .  com
}

From source file:mongodb.QuickTour.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 *//*  w w w.j  av  a 2 s . c  o m*/
public static void main(final String[] args) {

    //represents a pool of connections to the database
    MongoClient mongoClient = new MongoClient("10.9.17.105", 27017);

    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("test");

    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");

    // drop all the data in it
    collection.drop();

    // make a document and insert it
    Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1).append("info",
            new Document("x", 203).append("y", 102));

    collection.insertOne(doc);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    Document myDoc = collection.find().first();
    System.out.println(myDoc.toJson());

    // now, lets add lots of little documents to the collection so we can explore queries and cursors
    List<Document> documents = new ArrayList<Document>();
    for (int i = 0; i < 100; i++) {
        documents.add(new Document("i", i));
    }
    collection.insertMany(documents);
    System.out.println(
            "total # of documents after inserting 100 small ones (should be 101) " + collection.count());

    // find first
    myDoc = collection.find().first();
    System.out.println(myDoc.toJson());

    // lets get all the documents in the collection and print them out
    MongoCursor<Document> cursor = collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }

    for (Document cur : collection.find()) {
        System.out.println(cur.toJson());
    }

    // now use a query to get 1 document out
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc.toJson());

    // now use a range query to get a larger subset
    cursor = collection.find(gt("i", 50)).iterator();

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }

    // range query with multiple constraints
    cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator();

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }

    // Query Filters
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc.toJson());

    // now use a range query to get a larger subset
    Block<Document> printBlock = new Block<Document>() {
        @Override
        public void apply(final Document document) {
            System.out.println(document.toJson());
        }
    };
    collection.find(gt("i", 50)).forEach(printBlock);

    // filter where; 50 < i <= 100
    collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock);

    // Sorting
    myDoc = collection.find(exists("i")).sort(descending("i")).first();
    System.out.println(myDoc.toJson());

    // Projection
    myDoc = collection.find().projection(excludeId()).first();
    System.out.println(myDoc.toJson());

    // Update One
    collection.updateOne(eq("i", 10), new Document("$set", new Document("i", 110)));

    // Update Many
    UpdateResult updateResult = collection.updateMany(lt("i", 100),
            new Document("$inc", new Document("i", 100)));
    System.out.println(updateResult.getModifiedCount());

    // Delete One
    collection.deleteOne(eq("i", 110));

    // Delete Many
    DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
    System.out.println(deleteResult.getDeletedCount());

    collection.drop();

    // ordered bulk writes
    List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
    writes.add(new InsertOneModel<Document>(new Document("_id", 4)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 5)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 6)));
    writes.add(
            new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2))));
    writes.add(new DeleteOneModel<Document>(new Document("_id", 2)));
    writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4)));

    collection.bulkWrite(writes);

    collection.drop();

    collection.bulkWrite(writes, new BulkWriteOptions().ordered(false));
    collection.find().forEach(printBlock);

    // Clean up
    //        database.drop();

    // release resources
    mongoClient.close();
}

From source file:mongoSample.MongoSample.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args//from  w w w  .  ja v  a 2  s.  c  o m
 *            takes an optional single argument for the connection string
 */
public static void main(final String[] args) {
    String mongoServer = args[0];

    MongoClient mongoClient = new MongoClient(mongoServer);
    MongoDatabase database = mongoClient.getDatabase("sakila");
    MongoCollection<Document> collection = database.getCollection("test");

    // drop all the data in it
    collection.drop();

    // make a document and insert it
    Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1).append("info",
            new Document("x", 203).append("y", 102));

    collection.insertOne(doc);

    // get it (since it's the only one in there since we dropped the rest
    // earlier on)
    Document myDoc = collection.find().first();
    System.out.println(myDoc.toJson());

    // now, lets add lots of little documents to the collection so we can
    // explore queries and cursors
    List<Document> documents = new ArrayList<Document>();
    for (int i = 0; i < 100; i++) {
        documents.add(new Document("i", i));
    }
    collection.insertMany(documents);
    System.out.println(
            "total # of documents after inserting 100 small ones (should be 101) " + collection.count());

    // find first
    myDoc = collection.find().first();
    System.out.println(myDoc);
    System.out.println(myDoc.toJson());

    // lets get all the documents in the collection and print them out
    MongoCursor<Document> cursor = collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }

    for (Document cur : collection.find()) {
        System.out.println(cur.toJson());
    }

    // now use a query to get 1 document out
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc.toJson());

    // now use a range query to get a larger subset
    cursor = collection.find(gt("i", 50)).iterator();

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }

    // range query with multiple constraints
    cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator();

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }

    // Query Filters
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc.toJson());

    // now use a range query to get a larger subset
    Block<Document> printBlock = new Block<Document>() {
        @Override
        public void apply(final Document document) {
            System.out.println(document.toJson());
        }
    };
    collection.find(gt("i", 50)).forEach(printBlock);

    // filter where; 50 < i <= 100
    collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock);

    // Sorting
    myDoc = collection.find(exists("i")).sort(descending("i")).first();
    System.out.println(myDoc.toJson());

    // Projection
    myDoc = collection.find().projection(excludeId()).first();
    System.out.println(myDoc.toJson());

    // Update One
    collection.updateOne(eq("i", 10), new Document("$set", new Document("i", 110)));

    // Update Many
    UpdateResult updateResult = collection.updateMany(lt("i", 100),
            new Document("$inc", new Document("i", 100)));
    System.out.println(updateResult.getModifiedCount());

    // Delete One
    collection.deleteOne(eq("i", 110));

    // Delete Many
    DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
    System.out.println(deleteResult.getDeletedCount());

    collection.drop();

    // ordered bulk writes
    List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
    writes.add(new InsertOneModel<Document>(new Document("_id", 4)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 5)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 6)));
    writes.add(
            new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2))));
    writes.add(new DeleteOneModel<Document>(new Document("_id", 2)));
    writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4)));

    collection.bulkWrite(writes);

    collection.drop();

    collection.bulkWrite(writes, new BulkWriteOptions().ordered(false));
    // collection.find().forEach(printBlock);

    // Clean up
    //database.drop();

    // release resources
    mongoClient.close();
}

From source file:net.es.netshell.mongodb.MongoDBProvider.java

License:Open Source License

@Override
public void delete(String user, String name, PersistentObject obj) throws InstantiationException {
    String collectionName = user + "_" + name;
    if (!KernelThread.currentKernelThread().isPrivileged()) {
        throw new SecurityException("delete db one - not authorized");
    }/*from ww  w.  j a va  2s . c o m*/
    MongoCollection mongoCollection = this.db.getCollection(collectionName);
    if (mongoCollection == null) {
        throw new RuntimeErrorException(new Error("Could not store into collection " + collectionName));
    }
    Document query = new Document("resourceName", obj.getResourceName());
    mongoCollection.deleteMany(query);
}

From source file:net.es.netshell.mongodb.MongoDBProvider.java

License:Open Source License

@Override
public void delete(String user, String name, String objName) throws InstantiationException {
    String collectionName = user + "_" + name;
    if (!KernelThread.currentKernelThread().isPrivileged()) {
        throw new SecurityException("delete db one - not authorized");
    }//from   ww w  . j a  v  a 2  s . co m
    MongoCollection mongoCollection = this.db.getCollection(collectionName);
    if (mongoCollection == null) {
        throw new RuntimeErrorException(new Error("Could not store into collection " + collectionName));
    }
    Document query = new Document("resourceName", objName);
    mongoCollection.deleteMany(query);
}

From source file:net.netzgut.integral.mongo.internal.services.MongoODMImplementation.java

License:Apache License

@Override
public <T extends Serializable> DeleteResult deleteAll(Bson filter, Class<T> entityClass) {
    MongoCollection<Document> collection = this.mongo.getCollection(entityClass);
    return collection.deleteMany(filter);
}

From source file:net.netzgut.integral.mongo.utils.BatchOperations.java

License:Apache License

public static void replaceDocuments(MongoCollection<Document> collection, List<Document> documents) {

    // 1. Validation
    // BW decided emptying the collection via this method should always
    // be wrong, so ignore request if no new documents are coming.
    if (collection == null || documents == null || documents.isEmpty()) {
        return;/* w  ww.j  a va2  s  .  c o  m*/
    }

    // 2. Remove old data
    collection.deleteMany(new Document());

    // 3. Insert new data
    collection.insertMany(documents, new InsertManyOptions().ordered(true));
}

From source file:org.apache.metamodel.mongodb.mongo3.MongoDbDeleteBuilder.java

License:Apache License

@Override
public void execute() throws MetaModelException {
    final MongoCollection<Document> collection = _updateCallback.getCollection(getTable().getName());

    final MongoDbDataContext dataContext = _updateCallback.getDataContext();
    final Document query = dataContext.createMongoDbQuery(getTable(), getWhereItems());

    DeleteResult result = collection.deleteMany(query);
    logger.info("Remove returned result: {}", result);
}

From source file:org.apache.nifi.processors.mongodb.DeleteMongo.java

License:Apache License

@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();/*from w  w w .ja v  a  2  s . c om*/
    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);
    }
}

From source file:org.axonframework.mongo.eventsourcing.eventstore.AbstractMongoEventStorageStrategy.java

License:Apache License

@Override
public void deleteSnapshots(MongoCollection<Document> snapshotCollection, String aggregateIdentifier) {
    Bson mongoEntry = new BsonDocument(eventConfiguration.aggregateIdentifierProperty(),
            new BsonString(aggregateIdentifier));
    snapshotCollection.deleteMany(mongoEntry);
}