Example usage for com.mongodb DBCollection findOne

List of usage examples for com.mongodb DBCollection findOne

Introduction

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

Prototype

@Nullable
public DBObject findOne(final Object id) 

Source Link

Document

Get a single document from collection by '_id'.

Usage

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

License:Open Source License

private void joinTitle(final DBCollection title, final String inMstName, final String inMstEncoding,
        final int joinTag, final int newTag, final String outMstName)
        throws UnknownHostException, BrumaException {
    assert title != null;
    assert inMstName != null;
    assert inMstEncoding != null;
    assert joinTag > 0;
    assert newTag > 0;
    assert outMstName != null;

    final Master inMst = MasterFactory.getInstance(inMstName).setEncoding(inMstEncoding).open();
    final Master outMst = (Master) MasterFactory.getInstance(outMstName).asAnotherMaster(inMst).forceCreate();

    int cur = 0;/*from w w w.  ja  v a  2  s  . c  o m*/
    for (Record rec : inMst) {
        if (++cur % 10000 == 0) {
            System.out.println("++" + cur);
        }
        if (rec.isActive()) {
            //System.out.println("out encoding=" + outMstEncoding);                
            for (Field fld : rec.getFieldList(joinTag)) {
                final String str = removeAccents(fld.getContent()).toUpperCase();
                final BasicDBObject doc = (BasicDBObject) title.findOne(new BasicDBObject(INDEX_TAG, str));
                if (doc == null) {
                    //System.out.println("rec mfn=" + rec.getMfn() + " tag=" 
                    //        + INDEX_TAG + " content=" + fld.getContent());
                } else {
                    final BasicDBList lst = (BasicDBList) doc.get(RETURN_TAG);
                    for (Object obj : lst) {
                        rec.addField(newTag, (String) obj);
                    }
                }
            }
        }
        outMst.writeRecord(rec);

    }
    inMst.close();
    outMst.close();
}

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

License:Open Source License

public static boolean updateDocument(final DBCollection coll, final DBCollection hcoll, final String docId,
        final String fixedUrl, final String user, final boolean automatic) throws IOException {
    if (coll == null) {
        throw new NullPointerException("coll");
    }// w  w w  . j av a2 s  .c o m
    if (hcoll == null) {
        throw new NullPointerException("hcoll");
    }
    if (docId == null) {
        throw new NullPointerException("docId");
    }
    if (fixedUrl == null) {
        throw new NullPointerException("fixedUrl");
    }
    if (user == null) {
        throw new NullPointerException("user");
    }
    if (fixedUrl.length() >= 900) {
        throw new IOException("fixedUrl is too long >= 900. [" + fixedUrl + "]");
    }

    final BasicDBObject query = new BasicDBObject(ID_FIELD, docId);
    final BasicDBObject doc = (BasicDBObject) coll.findOne(query);

    if (doc == null) {
        throw new IOException("document not found id[" + docId + "]");
    }

    final BasicDBList lsthdoc;
    BasicDBObject hdoc = (BasicDBObject) hcoll.findOne(query);
    if (hdoc == null) {
        hdoc = new BasicDBObject();
        hdoc.append(ID_FIELD, docId);
        hdoc.append(MST_FIELD, (String) doc.get(MST_FIELD));
        hdoc.append(DATE_FIELD, (Date) doc.get(DATE_FIELD));
        lsthdoc = new BasicDBList();
        hdoc.append(ELEM_LST_FIELD, lsthdoc);
    } else {
        lsthdoc = (BasicDBList) hdoc.get(ELEM_LST_FIELD);
    }

    final String brokenUrl = doc.getString(BROKEN_URL_FIELD);
    final String brokenUrl_D = EncDecUrl.decodeUrl(brokenUrl);
    final String fixedUrl_E = EncDecUrl.encodeUrl(fixedUrl, CODEC, false);
    //final String fixedUrl_D = EncDecUrl.decodeUrl(fixedUrl);
    final BasicDBObject hcurdoc = new BasicDBObject();
    hcurdoc.append(BROKEN_URL_FIELD, brokenUrl).append(PRETTY_BROKEN_URL_FIELD, brokenUrl_D)
            .append(FIXED_URL_FIELD, fixedUrl_E).append(MSG_FIELD, (String) doc.get(MSG_FIELD))
            .append(CENTER_FIELD, (BasicDBList) doc.get(CENTER_FIELD)).append(AUTO_FIX_FIELD, automatic)
            .append(EXPORTED_FIELD, false).append(LAST_UPDATE_FIELD, new Date()).append(USER_FIELD, user);

    lsthdoc.add(0, hcurdoc);

    final boolean ret1 = coll.remove(doc, WriteConcern.ACKNOWLEDGED).getLastError().ok();
    final boolean ret2 = hcoll.save(hdoc).getLastError().ok();

    return ret1 && ret2;
}

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

License:Open Source License

public static boolean undoUpdateDocument(final DBCollection coll, final DBCollection hcoll, final String docId,
        final boolean updateBrokenColl) throws IOException {
    if (coll == null) {
        throw new NullPointerException("coll");
    }//from w w  w .  j a  v  a2  s .co m
    if (hcoll == null) {
        throw new NullPointerException("hcoll");
    }
    if (docId == null) {
        throw new NullPointerException("docId");
    }

    final BasicDBObject query = new BasicDBObject(ID_FIELD, docId);
    final BasicDBObject hdoc = (BasicDBObject) hcoll.findOne(query);

    if (hdoc == null) {
        throw new IOException("document not found id[" + docId + "]");
    }
    final BasicDBList lst = (BasicDBList) hdoc.get(ELEM_LST_FIELD);
    final BasicDBObject hcurdoc = (BasicDBObject) lst.remove(0);
    if (hcurdoc == null) {
        throw new IOException("document last element found. Id[" + docId + "]");
    }
    final BasicDBObject doc = new BasicDBObject();
    doc.put(DATE_FIELD, hdoc.get(DATE_FIELD));
    doc.put(LAST_UPDATE_FIELD, hcurdoc.get(LAST_UPDATE_FIELD));
    doc.put(MST_FIELD, hdoc.get(MST_FIELD));
    doc.put(ID_FIELD, docId);
    doc.put(BROKEN_URL_FIELD, hcurdoc.get(BROKEN_URL_FIELD));
    doc.put(PRETTY_BROKEN_URL_FIELD, hcurdoc.get(PRETTY_BROKEN_URL_FIELD));
    doc.put(MSG_FIELD, hcurdoc.get(MSG_FIELD));
    doc.put(CENTER_FIELD, hcurdoc.get(CENTER_FIELD));

    final boolean ret1 = updateBrokenColl ? coll.save(doc).getLastError().ok() : true;
    final boolean ret2;

    if (lst.isEmpty()) {
        ret2 = hcoll.remove(query, WriteConcern.ACKNOWLEDGED).getLastError().ok();
    } else {
        ret2 = hcoll.save(hdoc, WriteConcern.ACKNOWLEDGED).getLastError().ok();
    }

    return ret1 && ret2;
}

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

License:Open Source License

public static Set<String> filterCenterFields(final DBCollection coll, final Set<String> centerIds) {
    if (coll == null) {
        throw new NullPointerException("coll");
    }//from  w  w w  . j av  a2 s.c o m
    if (centerIds == null) {
        throw new NullPointerException("centerIds");
    }
    final Set<String> ret = new TreeSet<String>();

    for (String id : centerIds) {
        final BasicDBObject query = new BasicDBObject(CENTER_FIELD, id);
        final DBObject dbo = coll.findOne(query);
        if (dbo != null) {
            ret.add(id);
        }
    }

    return ret;
}

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

private void DownloadInfo() throws InterruptedException {
    //Verifica se j existe um banco de demanda criado no Mongo
    List<String> dbs = mongo.getDatabaseNames();
    if (!dbs.contains(assunto.toString())) {//Se o banco no existe, faz o download

        RestTemplate rt = new RestTemplate();
        DB territorios = mongo.getDB("territorios");
        DBCollection colTerritorios = territorios.getCollection("territorio");
        HttpEntity<String> entity = new HttpEntity<>("parameters", Processar.headers);
        BasicDBObject insert = new BasicDBObject();

        BasicDBObject insertDemanda = new BasicDBObject();

        DBCollection colDaDemanda = dbAssunto.getCollection(assunto.toString());

        System.out.println("db =" + dbAssunto);
        DBCollection k_classe = dbAssunto.getCollection("k");
        //K_CLASSES  -----------------------------------------------------------------------------------------------
        try {/*w ww  . j  a  v  a2  s .com*/

            ResponseEntity<domain.K_classes[]> kClasse = rt.exchange(
                    "http://xingu.lcc.unifesspa.edu.br:8080/api/k_classess?idassunto=" + assunto,
                    HttpMethod.GET, entity, domain.K_classes[].class);
            System.out.println("K-classe tamanho: " + kClasse.getBody().length);
            //System.out.println("Tamanho body:" + kClasse.getBody().length);
            for (domain.K_classes k : kClasse.getBody()) {
                insert.append("k_ordem", k.getk_ordem());
                insert.append("k_classes_id", k.getId());
                insert.append("ck", Integer.parseInt(k.getk_codigo()));
                insert.append("dk", k.getk_descricao());

                k_classe.insert(insert);
                insert.clear();

            }
            System.out.println("DEVERIA TER INSERIDO O K");
        } catch (Exception e) {
            e.printStackTrace();
            insert.clear();
        }
        //FIM K-CLASSES E COMEO INPUT_PRESENTES --------------------------------------------------------------------------------------------------------
        BasicDBObject insertCI = new BasicDBObject();
        try {
            System.out.println("Comeando a inserir os Inputs do assunto: " + assunto);
            ResponseEntity<domain.Input_presenteDTO[]> input = rt.exchange(
                    "http://xingu.lcc.unifesspa.edu.br:8080/api/input_presentes/getInputPresenteByAssantoId/"
                            + assunto,
                    HttpMethod.GET, entity, Input_presenteDTO[].class);
            System.out.println("Fez o download do assunto: " + assunto);
            System.out.println("Tamano input: " + input.getBody().length + "  Assunto: " + assunto);
            DBCollection colInput_presente = dbAssunto.getCollection("i"); // inserir assunto na base
            BasicDBObject search2 = new BasicDBObject();

            //    int cont = 0;
            for (Input_presenteDTO Input2 : input.getBody()) {
                //       System.out.println("Entrou");
                //Para a coleo "i"
                search2.append("ci", Integer.parseInt(Input2.getCodigo()));
                DBObject aux = colInput_presente.findOne(search2);
                if (aux != null) {
                    search2.clear();
                    // System.out.println("ja tem esse territorio inserido");
                } else {

                    DBCursor cursor = colTerritorios.find(search2);
                    while (cursor.hasNext()) {

                        aux = cursor.next();
                        // System.out.println("AUX: " + aux.toString());
                        if (Integer.parseInt(aux.get("ci").toString()) == Integer.parseInt(Input2.getCodigo())
                                && Integer.parseInt(aux.get("ano").toString()) == Integer
                                        .parseInt(Input2.getAno_ref())) {
                            // insertCI.append("uf_sigla", aux.get("uf_sigla"));
                            insertCI.append("longitude", Double.parseDouble(aux.get("longitude").toString()));
                            insertCI.append("latitude", Double.parseDouble(aux.get("latitude").toString()));
                            // System.out.println("Achou Territorio");
                        }

                    }
                    insertCI.append("ci", Integer.parseInt(Input2.getI_codigo_amc()));
                    insertCI.append("di", Input2.getTerritorio_nome());
                    insertCI.append("ano_ref", Integer.parseInt(aux.get("ano").toString()));
                    search2.clear();
                    colInput_presente.insert(insertCI);
                    insertCI.clear();
                }

                //Para a coleo com o mesmo nome da base
                insertDemanda.append("ci", Integer.parseInt(Input2.getI_codigo_amc()));
                insertDemanda.append("di", Input2.getTerritorio_nome());
                insertDemanda.append("ck", Integer.parseInt(Input2.getK_classesK_codigo()));
                insertDemanda.append("quant_valor", Double.parseDouble(Input2.getX_valor()));
                insertDemanda.append("ano", Integer.parseInt(Input2.getAno_ref()));

                //Aqui se acha a descrio da K-Classe envolvida, atravs do "k_classesK_codigo"                       
                search2.append("ck", Integer.parseInt(Input2.getK_classesK_codigo()));

                aux = k_classe.findOne(search2);
                insertDemanda.append("dk", (String) aux.get("dk"));
                search2.clear();

                //                    
                colDaDemanda.insert(insertDemanda);

                insertDemanda.clear();

                //   cont++;
                //   System.out.println(cont);
            }
            System.out.println("Inseriu input_presente do assunto: " + assunto);
            //Preparar banco------------------
            System.out.println("Preparando o assunto: " + assunto);
            datadao.prepareDatabase(false, dbAssunto);
            System.out.println("Fim preparar banco do assunto: " + assunto);
            //Fim preparar Banco----------
        } catch (Exception e) {
            e.printStackTrace();

            insert.clear();
            insertCI.clear();
        }

    } else {
        BasicDBObject search = new BasicDBObject();
        DB aux = mongo.getDB("demandas");
        DBCollection colDemandaAtiva = aux.getCollection("demandas_ativas");
        search.append("demanda", assunto.toString());
        boolean situacao = false;
        while (situacao == false) {

            DBCursor demanAtiva = colDemandaAtiva.find(search);
            if (demanAtiva.size() >= 1) {

                situacao = true;
            }
            Thread.currentThread().sleep(5000);
        }

    }

}

From source file:brooklyn.entity.nosql.mongodb.MongoDBTestHelper.java

License:Apache License

/** @return The {@link DBObject} representing the object with the given id */
public static DBObject getById(AbstractMongoDBServer entity, String id) {
    LOG.info("Getting {} from {}", new Object[] { id, entity });
    MongoClient mongoClient = clientForServer(entity);
    // Secondary preferred means the driver will let us read from secondaries too.
    mongoClient.setReadPreference(ReadPreference.secondaryPreferred());
    try {//from  w  ww . j a va 2  s. co  m
        DB db = mongoClient.getDB(TEST_DB);
        DBCollection testCollection = db.getCollection(TEST_COLLECTION);
        return testCollection.findOne(new BasicDBObject("_id", new ObjectId(id)));
    } finally {
        mongoClient.close();
    }
}

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

License:Open Source License

/**
 * Fetch a resource from the server via a given field value
 * @param collName the collection or database name
 * @param field1 the first field name/*from   w w  w  . j  av a  2 s.c  o m*/
 * @param value1 the value of the first field
 * @param field2 the second field name
 * @param value2 the value of the second field
 * @param field3 its field name
 * @param value3 the third value
 * @return the response as a string or null if not found
 */
private String getFromDbByThreeFields(String collName, String field1, String value1, String field2,
        String value2, String field3, String value3) throws DbException {
    try {
        connect();
        DBCollection coll = getCollectionFromName(collName);
        DBObject query = getThreeFieldQuery(field1, value1, field2, value2, field3, value3);
        DBObject obj = coll.findOne(query);
        if (obj != null)
            return obj.toString();
        else
            return null;
    } catch (Exception e) {
        throw new DbException(e);
    }
}

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

License:Open Source License

/**
 * Get the metadata as a string/*w  w w .  j a  va 2s.  com*/
 * @param docid its filename or docid
 * @return the metadata of the document as a string
 */
public String getMetadata(String docid) {
    try {
        connect();
        DBCollection collection = getCollectionFromName(Database.METADATA);
        DBObject query;
        query = new BasicDBObject(JSONKeys.DOCID, docid);
        DBObject obj = collection.findOne(query);
        if (obj != null) {
            obj.removeField(JSONKeys._ID);
            return obj.toString();
        } else
            return null;
    } catch (Exception e) {
        e.printStackTrace(System.out);
        return null;
    }
}

From source file:calliope.db.MongoConnection.java

License:Open Source License

/**
 * Fetch a resource from the server, or try to.
 * @param collName the collection or database name
 * @param docID the path to the resource in the collection
 * @return the response as a string or null if not found
 *///from ww w. j a  v a2s . c  om
@Override
public String getFromDb(String collName, String docID) throws AeseException {
    try {
        connect();
        DBCollection coll = getCollectionFromName(collName);
        DBObject query = new BasicDBObject(JSONKeys.DOCID, docID);
        DBObject obj = coll.findOne(query);
        if (obj != null)
            return obj.toString();
        else
            throw new FileNotFoundException("failed to find " + collName + "/" + docID);
    } catch (Exception e) {
        throw new AeseException(e);
    }
}

From source file:cfel.servlet.ImportCsvServlet.java

License:Open Source License

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/*from  w  w  w. ja va 2 s  .c o  m*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DBCollection collection = mDS.getCollection("photo");
    if (collection == null) {
        response.sendError(404, "No photo collection");
        return;
    }
    InputStream is = null;
    try {
        is = request.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine(); // Ignore header
        while ((line = br.readLine()) != null) {
            String[] values = getStrings(line);
            if (values.length == 2) {
                String portal_image_url = values[0];
                String class_id = values[1];
                System.out.println("url=" + portal_image_url + ", season=" + class_id);
                DBObject query = new BasicDBObject("portal_image_url", portal_image_url);
                DBObject photo = collection.findOne(query);
                if (photo == null) {
                    continue;
                }
                Object guessObj = photo.get("guess");
                if (guessObj instanceof List<?>) {
                    System.out.println(guessObj);
                    List<?> guess = (List<?>) guessObj;
                    Object lastGuess = guess.get(guess.size() - 1);
                    if (lastGuess instanceof DBObject
                            && class_id.equals(((DBObject) lastGuess).get("class_id"))) {
                        continue;
                    }
                }
                DBObject newGuess = new BasicDBObject();
                newGuess.put("updated", new Date());
                newGuess.put("class_id", class_id);
                DBObject update = new BasicDBObject("$push", new BasicDBObject("guess", newGuess));
                collection.update(photo, update, true, false);
            } else {
                System.err.println("Unknown data: " + line);
            }
        }

    } finally {
        if (is != null) {
            is.close();
        }
    }
    response.setStatus(200);
}