Example usage for com.mongodb DBCollection remove

List of usage examples for com.mongodb DBCollection remove

Introduction

In this page you can find the example usage for com.mongodb DBCollection remove.

Prototype

public WriteResult remove(final DBObject query, final DBCollectionRemoveOptions options) 

Source Link

Document

Remove documents from a collection.

Usage

From source file:com.andreig.jetty.WriteServlet.java

License:GNU General Public License

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.fine("doDelete()");

    if (!can_write(req)) {
        res.sendError(SC_UNAUTHORIZED);//from  w ww. j a  v a2  s . c o m
        return;
    }

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }

    DB db = mongo.getDB(db_name);

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    DBCollection col = db.getCollection(col_name);

    BufferedReader r = null;
    DBObject q = null;
    try {

        r = new BufferedReader(new InputStreamReader(is));
        String data = r.readLine();
        if (data == null) {
            error(res, SC_BAD_REQUEST, Status.get("no data"));
            return;
        }
        try {
            q = (DBObject) JSON.parse(data);
        } catch (JSONParseException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
            return;
        }

    } finally {
        if (r != null)
            r.close();
    }

    // search
    if (do_search) {

        DBCursor c = col.find(q);
        long l = c.count();
        String todelete[] = new String[(int) l];
        int n = 0;

        while (c.hasNext()) {

            DBObject o = c.next();
            ObjectId oid = (ObjectId) o.get("_id");
            String id = oid.toStringMongod();
            todelete[n++] = id;

        }
        c.close();
        search.get_writer().delete(todelete);

    }

    WriteResult wr = col.remove(q, write_concern);

    // return operation status
    if (do_return) {
        out_str(req, wr.toString());
        if (wr.getError() == null) {
            res.setStatus(SC_BAD_REQUEST);
            return;
        }
    }

    res.setStatus(SC_OK);

}

From source file:com.cyslab.craftvm.rest.mongo.WriteServlet.java

License:GNU General Public License

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doDelete()");

    if (!can_write(req)) {
        res.sendError(SC_UNAUTHORIZED);/*w w w .  j ava2s.  c  o m*/
        return;
    }

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }

    DB db = mongo.getDB(db_name);

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    DBCollection col = db.getCollection(col_name);

    BufferedReader r = null;
    DBObject q = null;
    try {

        r = new BufferedReader(new InputStreamReader(is));
        String data = r.readLine();
        if (data == null) {
            error(res, SC_BAD_REQUEST, Status.get("no data"));
            return;
        }
        try {
            q = (DBObject) JSON.parse(data);
        } catch (JSONParseException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
            return;
        }

    } finally {
        if (r != null)
            r.close();
    }

    // search
    if (do_search) {

        DBCursor c = col.find(q);
        long l = c.count();
        String todelete[] = new String[(int) l];
        int n = 0;

        while (c.hasNext()) {

            DBObject o = c.next();
            ObjectId oid = (ObjectId) o.get("_id");
            String id = oid.toStringMongod();
            todelete[n++] = id;

        }
        c.close();
        search.get_writer().delete(todelete);

    }

    WriteResult wr = col.remove(q, write_concern);

    // return operation status
    if (do_return) {
        out_str(req, wr.toString());
        if (wr.getError() == null) {
            res.setStatus(SC_BAD_REQUEST);
            return;
        }
    }

    res.setStatus(SC_OK);

}

From source file:com.ebay.jetstream.config.mongo.MongoDAO.java

License:MIT License

public static boolean removeConfigurationByQuery(BasicDBObject query, MongoConnection mongoConnection) {

    DBCollection dbCol = mongoConnection.getDBCollection();

    if (dbCol == null) {
        throw new MongoConfigRuntimeException("jetstreamconfig collection is unknown");
    }/*  w ww  .j ava 2  s.  c om*/

    try {
        if (query == null) {
            return false;
        }

        WriteResult result = dbCol.remove(query, WriteConcern.SAFE);

        if (result.getLastError().ok()) {
            return true;
        }

    } catch (Exception err) {
        throw new MongoConfigRuntimeException(err);
    }

    return true;
}

From source file:com.ebay.jetstream.configurationmanagement.MongoLogDAO.java

License:MIT License

public static boolean removeConfigurationByQuery(BasicDBObject query, MongoLogConnection mongoLogConnection) {

    DBCollection dbCol = mongoLogConnection.getDBCollection();

    if (dbCol == null) {
        throw new MongoConfigRuntimeException("jetstreamconfig collection is unknown");
    }//  w  w  w  . j  ava  2s  .co m

    try {
        if (query == null) {
            return false;
        }

        WriteResult result = dbCol.remove(query, WriteConcern.SAFE);

        if (result.getLastError().ok()) {
            return true;
        }

    } catch (Exception err) {
        throw new MongoConfigRuntimeException(err);
    }

    return true;
}

From source file:com.socialsky.mods.MongoPersistor.java

License:Apache License

private void doDelete(Message<JsonObject> message) {
    String collection = getMandatoryString("collection", message);
    if (collection == null) {
        return;/*from w  ww .j  a  va 2 s. co  m*/
    }
    JsonObject matcher = getMandatoryObject("matcher", message);
    if (matcher == null) {
        return;
    }
    DBCollection coll = db.getCollection(collection);
    DBObject obj = jsonToDBObject(matcher);
    WriteConcern writeConcern = WriteConcern.valueOf(getOptionalStringConfig("writeConcern", ""));
    // Backwards compatibility
    if (writeConcern == null) {
        writeConcern = WriteConcern.valueOf(getOptionalStringConfig("write_concern", ""));
    }

    if (writeConcern == null) {
        writeConcern = db.getWriteConcern();
    }
    WriteResult res = coll.remove(obj, writeConcern);
    int deleted = res.getN();
    JsonObject reply = new JsonObject().putNumber("number", deleted);
    sendOK(message, reply);
}

From source file:eu.europeana.corelib.edm.utils.construct.FullBeanHandler.java

public boolean removeRecord(SolrServer solrServer, RDF rdf) {
    try {// ww w . j av  a  2  s  .  c  om
        solrServer.deleteByQuery(
                "europeana_id:" + ClientUtils.escapeQueryChars(rdf.getProvidedCHOList().get(0).getAbout()));

        DBCollection records = mongoServer.getDatastore().getDB().getCollection("record");
        DBCollection proxies = mongoServer.getDatastore().getDB().getCollection("Proxy");
        DBCollection providedCHOs = mongoServer.getDatastore().getDB().getCollection("ProvidedCHO");
        DBCollection aggregations = mongoServer.getDatastore().getDB().getCollection("Aggregation");
        DBCollection europeanaAggregations = mongoServer.getDatastore().getDB()
                .getCollection("EuropeanaAggregation");
        DBCollection physicalThing = mongoServer.getDatastore().getDB().getCollection("PhysicalThing");
        DBObject query = new BasicDBObject("about", rdf.getProvidedCHOList().get(0).getAbout());
        DBObject proxyQuery = new BasicDBObject("about",
                "/proxy/provider" + rdf.getProvidedCHOList().get(0).getAbout());
        DBObject europeanaProxyQuery = new BasicDBObject("about",
                "/proxy/europeana" + rdf.getProvidedCHOList().get(0).getAbout());

        DBObject providedCHOQuery = new BasicDBObject("about",
                "/item" + rdf.getProvidedCHOList().get(0).getAbout());
        DBObject aggregationQuery = new BasicDBObject("about",
                "/aggregation/provider" + rdf.getProvidedCHOList().get(0).getAbout());
        DBObject europeanaAggregationQuery = new BasicDBObject("about",
                "/aggregation/europeana" + rdf.getProvidedCHOList().get(0).getAbout());
        europeanaAggregations.remove(europeanaAggregationQuery, WriteConcern.FSYNC_SAFE);
        records.remove(query, WriteConcern.FSYNC_SAFE);
        proxies.remove(europeanaProxyQuery, WriteConcern.FSYNC_SAFE);
        proxies.remove(proxyQuery, WriteConcern.FSYNC_SAFE);
        physicalThing.remove(europeanaProxyQuery, WriteConcern.FSYNC_SAFE);
        physicalThing.remove(proxyQuery, WriteConcern.FSYNC_SAFE);
        providedCHOs.remove(providedCHOQuery, WriteConcern.FSYNC_SAFE);
        aggregations.remove(aggregationQuery, WriteConcern.FSYNC_SAFE);
        return true;
    } catch (SolrServerException e) {
        log.log(Level.SEVERE, e.getMessage());

    } catch (IOException e) {
        log.log(Level.SEVERE, e.getMessage());

    }
    return false;
}

From source file:eu.europeana.corelib.edm.utils.construct.FullBeanHandler.java

public boolean removeRecordById(SolrServer solrServer, String id) {
    try {//ww  w .j a  v a2s.c  om
        solrServer.deleteByQuery("europeana_id:" + ClientUtils.escapeQueryChars(id));

        DBCollection records = mongoServer.getDatastore().getDB().getCollection("record");
        DBCollection proxies = mongoServer.getDatastore().getDB().getCollection("Proxy");
        DBCollection providedCHOs = mongoServer.getDatastore().getDB().getCollection("ProvidedCHO");
        DBCollection aggregations = mongoServer.getDatastore().getDB().getCollection("Aggregation");
        DBCollection europeanaAggregations = mongoServer.getDatastore().getDB()
                .getCollection("EuropeanaAggregation");
        DBCollection physicalThing = mongoServer.getDatastore().getDB().getCollection("PhysicalThing");
        DBObject query = new BasicDBObject("about", id);
        DBObject proxyQuery = new BasicDBObject("about", "/proxy/provider" + id);
        DBObject europeanaProxyQuery = new BasicDBObject("about", "/proxy/europeana" + id);

        DBObject providedCHOQuery = new BasicDBObject("about", "/item" + id);
        DBObject aggregationQuery = new BasicDBObject("about", "/aggregation/provider" + id);
        DBObject europeanaAggregationQuery = new BasicDBObject("about", "/aggregation/europeana" + id);
        europeanaAggregations.remove(europeanaAggregationQuery, WriteConcern.FSYNC_SAFE);
        records.remove(query, WriteConcern.FSYNC_SAFE);
        proxies.remove(europeanaProxyQuery, WriteConcern.FSYNC_SAFE);
        proxies.remove(proxyQuery, WriteConcern.FSYNC_SAFE);
        physicalThing.remove(europeanaProxyQuery, WriteConcern.FSYNC_SAFE);
        physicalThing.remove(proxyQuery, WriteConcern.FSYNC_SAFE);
        providedCHOs.remove(providedCHOQuery, WriteConcern.FSYNC_SAFE);
        aggregations.remove(aggregationQuery, WriteConcern.FSYNC_SAFE);
        return true;
    } catch (SolrServerException e) {
        log.log(Level.SEVERE, e.getMessage());

    } catch (IOException e) {
        log.log(Level.SEVERE, e.getMessage());

    }
    return false;
}

From source file:eu.europeana.corelib.edm.utils.construct.FullBeanHandler.java

public void clearData(String collection) {
    DBCollection records = mongoServer.getDatastore().getDB().getCollection("record");
    DBCollection proxies = mongoServer.getDatastore().getDB().getCollection("Proxy");
    DBCollection physicalThing = mongoServer.getDatastore().getDB().getCollection("PhysicalThing");
    DBCollection providedCHOs = mongoServer.getDatastore().getDB().getCollection("ProvidedCHO");
    DBCollection aggregations = mongoServer.getDatastore().getDB().getCollection("Aggregation");
    DBCollection europeanaAggregations = mongoServer.getDatastore().getDB()
            .getCollection("EuropeanaAggregation");

    DBObject query = new BasicDBObject("about", Pattern.compile("^/" + collection + "/"));
    DBObject proxyQuery = new BasicDBObject("about", Pattern.compile("^/proxy/provider/" + collection + "/"));
    DBObject europeanaProxyQuery = new BasicDBObject("about",
            Pattern.compile("^/proxy/europeana/" + collection + "/"));

    DBObject providedCHOQuery = new BasicDBObject("about", Pattern.compile("^/item/" + collection + "/"));
    DBObject aggregationQuery = new BasicDBObject("about",
            Pattern.compile("^/aggregation/provider/" + collection + "/"));
    DBObject europeanaAggregationQuery = new BasicDBObject("about",
            Pattern.compile("^/aggregation/europeana/" + collection + "/"));
    europeanaAggregations.remove(europeanaAggregationQuery, WriteConcern.REPLICAS_SAFE);
    records.remove(query, WriteConcern.REPLICAS_SAFE);
    proxies.remove(europeanaProxyQuery, WriteConcern.REPLICAS_SAFE);
    proxies.remove(proxyQuery, WriteConcern.REPLICAS_SAFE);
    physicalThing.remove(proxyQuery, WriteConcern.REPLICAS_SAFE);
    physicalThing.remove(europeanaProxyQuery, WriteConcern.REPLICAS_SAFE);
    providedCHOs.remove(providedCHOQuery, WriteConcern.REPLICAS_SAFE);
    aggregations.remove(aggregationQuery, WriteConcern.REPLICAS_SAFE);
}

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

License:Apache License

@Override
public void execute() throws MetaModelException {
    final DBCollection collection = _updateCallback.getCollection(getTable().getName());

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

    WriteConcern writeConcern = _updateCallback.getWriteConcernAdvisor().adviceDeleteQuery(collection, query);

    final WriteResult writeResult = collection.remove(query, writeConcern);
    logger.info("Remove returned result: {}", writeResult);
}

From source file:org.aw20.mongoworkbench.command.RemoveMongoCommand.java

License:Open Source License

@Override
public void execute() throws Exception {
    MongoClient mdb = MongoFactory.getInst().getMongo(sName);

    if (mdb == null)
        throw new Exception("no server selected");

    if (sDb == null)
        throw new Exception("no database selected");

    MongoFactory.getInst().setActiveDB(sDb);

    DB db = mdb.getDB(sDb);/*from   w w  w.j a  va 2s. co m*/
    BasicDBObject cmdMap = parseMongoCommandString(db, cmd);

    if (!cmdMap.containsField("removeArgs"))
        throw new Exception("no remove document");

    DBCollection collection = db.getCollection(sColl);

    BasicDBList args = (BasicDBList) cmdMap.get("removeArgs");

    // Run the command
    db.requestStart();
    WriteResult writeresult;
    try {
        writeresult = collection.remove((DBObject) args.get(0), WriteConcern.JOURNAL_SAFE);
    } finally {
        db.requestDone();
    }

    // Get the result
    Map mwriteresult = (Map) JSON.parse(writeresult.toString());
    mwriteresult.put("exeDate", new Date());

    EventWorkBenchManager.getInst().onEvent(Event.WRITERESULT, mwriteresult);

    setMessage("Removed");
}