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) 

Source Link

Document

Remove documents from a collection.

Usage

From source file:br.bireme.scl.BrokenLinks.java

License:Open Source License

public static int createLinks(final String outCheckFile, final String outEncoding, final String mstName,
        final String mstEncoding, final String host, final int port, final String user, final String password,
        final boolean clearCol, final String[] allowedMessages) throws BrumaException, IOException {
    if (outCheckFile == null) {
        throw new NullPointerException("outCheckFile");
    }//www . j a  va2s . c  o m
    if (outEncoding == null) {
        throw new NullPointerException("outEncoding");
    }
    if (mstName == null) {
        throw new NullPointerException("mstName");
    }
    if (mstEncoding == null) {
        throw new NullPointerException("mstEncoding");
    }
    if (host == null) {
        throw new NullPointerException("host");
    }
    if (port <= 0) {
        throw new IllegalArgumentException("port <= 0");
    }
    if (allowedMessages == null) {
        throw new NullPointerException("allowedMessages");
    }

    final Master mst = MasterFactory.getInstance(mstName).setEncoding(mstEncoding).open();
    final String mName = new File(mst.getMasterName()).getName();
    final BufferedReader in = new BufferedReader(
            new InputStreamReader(new FileInputStream(outCheckFile), outEncoding));
    final MongoClient mongoClient = new MongoClient(host, port);
    final DB db = mongoClient.getDB(SOCIAL_CHECK_DB);
    // map -> mfn ->  url,occ
    final Map<Integer, Map<String, Integer>> occMap = new HashMap<Integer, Map<String, Integer>>();
    final boolean checkPassword = false;
    if (checkPassword) {
        final boolean auth = db.authenticate(user, password.toCharArray());
        if (!auth) {
            throw new IllegalArgumentException("invalid user/password");
        }
    }

    final DBCollection coll = db.getCollection(BROKEN_LINKS_COL);
    final DBCollection ccColl = db.getCollection(CC_FIELDS_COL);
    final DBCollection hColl = db.getCollection(HISTORY_COL);

    if (ccColl.findOne() == null) {
        if (!createCcFieldsCollection(ccColl)) {
            throw new IOException("CC fields collection creation failed");
        }
    }
    final int idTag = getIsisIdField(mName, ccColl);
    final int urlTag = getIsisUrlFields(mName, ccColl);
    if (urlTag <= 0) {
        throw new IOException("Missing Isis url fields");
    }
    final List<Integer> tags = getIsisCcFields(mName, ccColl);
    final Set<String> allowedMess = new HashSet<String>(Arrays.asList(allowedMessages));
    final Map<String, Integer> idMap = getIdMfn(mst, idTag);
    int tell = 0;
    int tot = 0;

    if (clearCol) {
        coll.dropIndexes();
        coll.remove(new BasicDBObject());
    }

    System.out.println("Saving documents ...");
    while (true) {
        final String line = in.readLine();
        if (line == null) {
            break;
        }
        final String lineT = line.trim();
        if (!lineT.isEmpty()) {
            final String[] split = lineT.split(" *\\| *", 4); //id|url|msg|master
            if (split.length < 4) {
                throw new IOException("Wrong line format: " + line);
            }
            final int openPos = split[2].indexOf('('); // cut extra data               
            final String prefix = (openPos > 0) ? split[2].substring(0, openPos) : split[2];

            if (allowedMess.contains(prefix.trim())) {
                final Integer id = idMap.get(split[0]);
                if (id == null) {
                    throw new IOException("id[" + split[0] + "] not found");
                }

                final String url_e = EncDecUrl.encodeUrl(split[1], outEncoding, false);

                saveRecord(mName, id, url_e, split[2], urlTag, tags, mst, coll, hColl, occMap);
                tot++;
            }
            if (++tell % 5000 == 0) {
                System.out.println("++" + tell);
            }
        }
    }

    System.out.print("\nFixing urls that do not start with http:// ... ");
    MongoOperations.fixMissingHttp(coll, hColl);
    System.out.println(" - OK");

    //removeOldDocs(coll);

    if (clearCol) {
        createIndex(coll);
    }

    in.close();
    mst.close();

    return tot;
}

From source file:br.edu.unifesspa.lcc.indexer.GerarIndice.java

@Override
public void run() {
    if (!list.isEmpty()) {

        //Foi identificado um problema quando h poucos processamentos agendados,
        // ocorre de processar mais que uma vez, ao mesmo tempo, o mesmo Processamento Id, portando,  necessario remover o
        //processamento_indice do banco,quando comear o processamento
        //Fazer download da demanda----
        try {// ww w.  java2  s .  c o m
            DownloadInfo();
        } catch (InterruptedException ex) {
            // Logger.getLogger(GerarIndice.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }
        //Fim de Fazer download da demada----

        //Insere em um banco, especificando qual assunto, a demanda est utilizando
        BasicDBObject search = new BasicDBObject();
        DB aux = mongo.getDB("demandas");
        DBCollection colDemandaAtiva = aux.getCollection("demandas_ativas");
        search.append("demanda", assunto.toString());
        search.append("Processamento_indiceId", procId);
        System.out.println("Inseriu na demanda_ativa");
        colDemandaAtiva.insert(search);
        //Fim inserir no banco, a demanda ativa

        //Aqui itera sobre a lista de indicadores que devem ser processados
        System.out.println("Est para entrar no forit e a lista : " + list);
        for (Integer integer : list) {
            try {
                System.out.println("Processando indicador: " + integer);
                est.getIndicador(integer, dbAssunto); //Gera o indicador
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //Depois de processar todos os indices, remove do banco das demandas_ativas, o assunto que foi processado.
        colDemandaAtiva.remove(search);
        System.out.println("REMOVEU");
        search.clear();

        //Se no tiver mais nenhuma demanda utilizando o assunto, dropa-se o banco da demanda
        search.append("demanda", assunto.toString());
        DBCursor cursor = colDemandaAtiva.find(search);
        if (cursor.size() == 0) {
            //dbAssunto.dropDatabase();
            System.out.println("DROPOU");

        }
    }
}

From source file:br.rdu.ifpb.mongo.repositorio.PessoaRepositoriMongo.java

@Override
public int remove(String key, String value) {

    DB db = getConnection();/* ww w  . ja  v  a2 s .  c om*/
    DBCollection table = db.getCollection("pessoa");
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put(key, value);

    result = table.remove(searchQuery).getN();
    closeConnection(mongo);
    return result;
}

From source file:BusinessLogic.Service.RestaurantService.java

public String delete(String name) {
    String deleteReservation = null;
    try {//from ww w .  ja v a  2s  .c  o  m
        // To connect to mongo dbserver
        MongoConnection dbSingleton = MongoConnection.getInstance();
        DB db = dbSingleton.getTestdb();
        DBCollection coll = db.getCollection(collName);

        System.out.println("Collection restaurants selected successfully");

        BasicDBObject whereQuery = new BasicDBObject();
        // Sentence to search one account number
        whereQuery.put("name", name);

        DBCursor cursor = coll.find(whereQuery);

        coll.remove(whereQuery);
        System.out.println("Document deleted successfully");
        deleteReservation = "Success";

    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
    if (deleteReservation != null) {
        return "The restaurant has been deleted successfully!";
    } else {
        return "The restaurant has not been deleted!";
    }

}

From source file:calliope.core.database.MongoConnection.java

License:Open Source License

private String removeFromDbByThreeFields(String collName, String field1, String value1, String field2,
        String value2, String field3, String value3) throws DbException {
    try {/* w w w .  j av  a  2  s . co m*/
        connect();
        DBCollection coll = getCollectionFromName(collName);
        DBObject query = getThreeFieldQuery(field1, value1, field2, value2, field3, value3);
        WriteResult result = coll.remove(query);
        if (result != null)
            return result.toString();
        else
            return null;
    } catch (Exception e) {
        throw new DbException(e);
    }
}

From source file:calliope.core.database.MongoConnection.java

License:Open Source License

/**
 * Remove a document from the database by a unique field value
 * @param collName name of the collection
 * @param field the name of the field /*  w ww.  j a  v  a 2  s.c  om*/
 * @param value the value of the field
 * @return the server response
 */
@Override
public String removeFromDbByField(String collName, String field, String value) throws DbException {
    try {
        connect();
        DBCollection coll = getCollectionFromName(collName);
        //new BasicDBObject("_id", new ObjectId(idString));
        Object obj = value;
        if (field.equals(JSONKeys._ID))
            obj = new ObjectId(value);
        DBObject query = new BasicDBObject(field, obj);
        WriteResult result = coll.remove(query);
        return result.toString();
    } catch (Exception e) {
        throw new DbException(e);
    }
}

From source file:calliope.core.database.MongoConnection.java

License:Open Source License

/**
 * Remove an entire set of documents that match a regular expression.
 * @param collName the collection to remove from
 * @param key the key field to match//from w w  w.j  a v  a 2  s  . com
 * @param expr the regular expression for key's values
 * @return the result
 * @throws DbException 
 */
public String removeFromDbByExpr(String collName, String key, String expr) throws DbException {
    try {
        DBCollection coll = getCollectionFromName(collName);
        if (coll != null) {
            BasicDBObject q = new BasicDBObject();
            q.put(key, Pattern.compile(expr));
            WriteResult result = coll.remove(q);
            return result.toString();
        } else
            throw new Exception("Collection " + collName + " not found");
    } catch (Exception e) {
        throw new DbException(e);
    }
}

From source file:calliope.db.MongoConnection.java

License:Open Source License

/**
 * Remove a document from the database//  ww  w.j a va 2  s  . c  o m
 * @param collName name of the collection
 * @param docID the docid of the resource 
 * @param json the json to put there
 * @return the server response
 */
@Override
public String removeFromDb(String collName, String docID) throws AeseException {
    try {
        connect();
        DBCollection coll = getCollectionFromName(collName);
        DBObject query = new BasicDBObject(JSONKeys.DOCID, docID);
        WriteResult result = coll.remove(query);
        return result.toString();
    } catch (Exception e) {
        throw new AeseException(e);
    }
}

From source file:cfel.servlet.ServiceServlet.java

License:Open Source License

/**
 * @see HttpServlet#doDelete(HttpServletRequest, HttpServletResponse)
 * /*from  w ww  .java 2 s .com*/
 *      Delete a resource
 */
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String type = request.getParameter("type");
    String id = request.getParameter("id");
    System.out.println("doDelete: type=" + type + " id=" + id);

    if (id == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Delete all is not supported");
        return;
    }

    if ("file".equals(type)) {
        // Delete a file
        if (mDS.getFile(id) == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("File %s does not exist", id));
            return;
        }
        mDS.deleteFile(id);
        return;
    }

    DBCollection collection = mDS.getCollection(type);
    if (collection == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("Unknown collection %s", type));
        return;
    }

    // Delete a document
    DBObject obj = collection.findOne(new ObjectId(id));
    if (obj == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("Document %s does not exist", id));
        return;
    }
    sendJSON(collection.remove(obj), response);
}

From source file:co.edu.uniandes.csw.Arquidalgos.usuario.persistence._UsuarioPersistence.java

License:MIT License

public void deleteUsuarioNoSql(String id) {

    DBCollection coll = null;
    BasicDBObject doc = new BasicDBObject();

    coll = db.getCollection("UsuarioDTO");

    doc.append("facebookId", id);
    coll.remove(doc);
}