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.shampan.model.LoginAttemptModel.java

/**
 * this method will remove all login attempts of a user
 *
 * @param email *//  www  .  j  av a2s .  co m
 */
public ResultEvent clearLoginAttempts(String email) {
    try {
        MongoCollection<LoginAttemptDAO> mongoCollection = DBConnection.getInstance().getConnection()
                .getCollection(Collections.LOGINATTEMPTS.toString(), LoginAttemptDAO.class);
        Document selectDocument = new Document();
        selectDocument.put("login", email);
        mongoCollection.deleteMany(selectDocument);
        this.getResultEvent().setResponseCode(PropertyProvider.get("SUCCESSFUL_OPERATION"));
    } catch (Exception ex) {
        this.getResultEvent().setResponseCode(PropertyProvider.get("ERROR_EXCEPTION"));
    }
    return this.resultEvent;
}

From source file:com.threecrickets.prudence.cache.HazelcastMongoDbMapStore.java

License:LGPL

public void deleteAll(Collection<K> keys) {
    MongoCollection<Document> collection = getCollection();
    Document query = new Document();
    Document in = new Document();

    query.put("_id", in);
    in.put("$in", keys);

    collection.deleteMany(query);
}

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

License:Apache License

@Override
public void asyncDelete(String database, String collection, boolean singleRemove, BsonDocument selector)
        throws MongoException {
    try {//ww  w. j  a  v a  2  s .  com
        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);
        }
    }
}

From source file:data.Project.java

License:Open Source License

public void deleteFromDb(DBManagerMongo manager) throws Exception {
    MongoCollection<Document> coll = manager.getDb().getCollection("project");
    DeleteResult result = coll.deleteOne(and(eq("id", getId()), eq("hash", getRemoteHash())));
    if (result.getDeletedCount() != 1)
        throw new Exception("Record was modyfied or not found");

    MongoCollection members = manager.getDb().getCollection("project_member");
    members.deleteMany(eq("project_id", getId()));

    MongoCollection phases = manager.getDb().getCollection("project_phase");
    phases.deleteMany(eq("project_id", getId()));

    MongoCollection activities = manager.getDb().getCollection("activity");
    activities.deleteMany(eq("project_id", getId()));
}

From source file:data.ProjectMember.java

License:Open Source License

public void deleteFromDb(DBManagerMongo manager) throws Exception {
    MongoCollection<Document> coll = manager.getDb().getCollection("project_member");
    DeleteResult result = coll//from  w  w  w  .j ava 2  s  . c o  m
            .deleteOne(and(and(eq("user_login_name", getUserLoginName()), eq("hash", getRemoteHash())),
                    eq("project_id", getProjectId())));
    if (result.getDeletedCount() != 1)
        throw new Exception("Record was modyfied or not found");

    MongoCollection activity = manager.getDb().getCollection("activity");
    activity.deleteMany(and(eq("project_id", getProjectId()), eq("user_login_name", getUserLoginName())));
}

From source file:data.ProjectPhase.java

License:Open Source License

public void deleteFromDb(DBManagerMongo manager) throws Exception {
    MongoCollection<Document> coll = manager.getDb().getCollection("project_phase");
    DeleteResult result = coll.deleteOne(and(eq("id", getId()), eq("hash", getRemoteHash())));
    if (result.getDeletedCount() != 1)
        throw new Exception("Record was modyfied or not found");

    MongoCollection activities = manager.getDb().getCollection("activity");
    activities.deleteMany(eq("project_phase_id", getId()));
}

From source file:data.User.java

License:Open Source License

public void deleteFromDb(DBManagerMongo manager) throws Exception {
    ArrayList<Project> ownedProjects = Project.getProjectsByUserName(getLoginName(), manager);
    for (Project p : ownedProjects)
        p.deleteFromDb(manager);/*from  ww w .  j a v  a  2 s.  c  om*/

    MongoCollection<Document> coll = manager.getDb().getCollection("user");
    DeleteResult result = coll.deleteOne(and(eq("login_name", getLoginName()), eq("hash", getRemoteHash())));
    if (result.getDeletedCount() != 1)
        throw new Exception("Record was modyfied or not found");

    MongoCollection members = manager.getDb().getCollection("project_member");
    members.deleteMany(eq("user_login_name", getLoginName()));

    MongoCollection activities = manager.getDb().getCollection("activity");
    activities.deleteMany(eq("user_login_name", getLoginName()));

    MongoCollection project = manager.getDb().getCollection("project");
    project.deleteMany(eq("user_login_name", getLoginName()));
}

From source file:data.User.java

License:Open Source License

public void deleteFromDB(DBManagerMongo manager) throws Exception {
    ArrayList<Project> ownedProjects = Project.getProjectsByUserName(getLoginName(), manager);
    for (Project p : ownedProjects)
        p.deleteFromDb(manager);//from  w w w . j ava 2s  . c o m

    MongoCollection<Document> coll = manager.getDb().getCollection("user");
    DeleteResult result = coll.deleteOne(and(eq("login_name", getLoginName()), eq("hash", getRemoteHash())));
    if (result.getDeletedCount() != 1)
        throw new Exception("Record was modyfied or not found");

    MongoCollection members = manager.getDb().getCollection("project_member");
    members.deleteMany(eq("user_login_name", getLoginName()));

    MongoCollection activities = manager.getDb().getCollection("activity");
    activities.deleteMany(eq("user_login_name", getLoginName()));

    MongoCollection project = manager.getDb().getCollection("project");
    project.deleteMany(eq("user_login_name", getLoginName()));
}

From source file:examples.tour.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
 *///from  w  ww .ja va 2 s.co  m
public static void main(final String[] args) {
    MongoClient mongoClient;

    if (args.length == 0) {
        // connect to the local database server
        mongoClient = new MongoClient();
    } else {
        mongoClient = new MongoClient(new MongoClientURI(args[0]));
    }

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

    // 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>() {

        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());

    // Aggregation
    collection
            .aggregate(
                    asList(match(gt("i", 0)), project(Document.parse("{ITimes10: {$multiply: ['$i', 10]}}"))))
            .forEach(printBlock);

    myDoc = collection.aggregate(singletonList(group(null, sum("total", "$i")))).first();
    System.out.println(myDoc.toJson());

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

    // Update Many
    UpdateResult updateResult = collection.updateMany(lt("i", 100), inc("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:henu.dao.impl.CaclDaoImpl.java

License:Open Source License

@Override
public boolean deleteUserDate(String cid, String uid) {
    MongoCollection<Document> collection = NosqlDB.getCollection(cid);

    collection.deleteMany(Filters.eq("uid", uid));
    return true;/*  ww w  .j  a v a 2 s . c o  m*/
}