Example usage for com.mongodb DBCollection find

List of usage examples for com.mongodb DBCollection find

Introduction

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

Prototype

public DBCursor find() 

Source Link

Document

Select all documents in collection and get a cursor to the selected documents.

Usage

From source file:app.model.Model.java

public void setTable(JTable table, String collection) {
    DBCollection col = this.getCollection(collection);
    DBCursor cur = col.find();

    String[] columnNames = { "id", "CIDADE", "UF" };
    DefaultTableModel model = new DefaultTableModel(columnNames, 0);

    while (cur.hasNext()) {
        DBObject obj = cur.next();//from   w  ww.j av a2s . c o  m
        String cidade = (String) obj.get("CIDADE");
        String uf = (String) obj.get("UF");
        ObjectId id = (ObjectId) obj.get("_id");
        model.addRow(new Object[] { id, cidade, uf });
    }
    cur.close();
    table.setModel(model);
}

From source file:app.ui.Init.java

public void setTable() {
    String collection = cbDelta.getSelectedItem().toString().trim() + "_formated_"
            + cbOL.getSelectedItem().toString().toLowerCase().replace("-", "");
    collection = collection.replace("rollup", "dice_rollup");
    collection = collection.replace("drilldown", "dice_drilldown_formated");
    DBCollection col = model.getCollection(collection);
    DBCursor cur = col.find();

    String[] columnNames = Util.getAttsNames(collection);
    String[] pseudoColumns = new String[columnNames.length + 1];
    String[] values = new String[columnNames.length + 1];

    for (int i = 0; i < columnNames.length; i++) {
        pseudoColumns[i] = columnNames[i];
    }//from   w  w  w.  j a  va  2s . com
    pseudoColumns[pseudoColumns.length - 1] = lsM.getSelectedValue().toString().trim();

    DefaultTableModel model = new DefaultTableModel(pseudoColumns, 0);

    for (int i = 0; i < pseudoColumns.length; i++) {
        pseudoColumns[i] = "_key" + (1 + i);
    }
    pseudoColumns[pseudoColumns.length - 1] = "_value";

    while (cur.hasNext()) {
        DBObject obj = cur.next();

        for (int i = 0; i < values.length - 1; i++) {
            values[i] = (String) obj.get(pseudoColumns[i]);
        }
        values[values.length - 1] = obj.get(pseudoColumns[values.length - 1]).toString();
        /*String cidade = (String) obj.get("CIDADE");
        String uf = (String) obj.get("UF");
        ObjectId id = (ObjectId) obj.get("_id");
        */

        //model.addRow(new Object[]{id, cidade, uf});
        //model.addRow(new Object[]{values});
        Object[] newObj = new Object[values.length];
        //{values}
        for (int i = 0; i < values.length; i++) {
            newObj[i] = values[i];
        }
        model.addRow(newObj);
    }
    cur.close();
    tbCR.setModel(model);
}

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

License:Open Source License

private static boolean removeOldDocs(final DBCollection coll) {
    assert coll != null;

    final Date now = new Date();
    final DBCursor cursor = coll.find();
    boolean ret = true;

    while (cursor.hasNext()) {
        final BasicDBObject obj = (BasicDBObject) cursor.next();
        final Date auxDate = obj.getDate(LAST_UPDATE_FIELD);
        if ((auxDate == null) || (now.getTime() - auxDate.getTime()) > 60 * 60 * 1000) {
            final WriteResult wr = coll.remove(obj, WriteConcern.ACKNOWLEDGED);
            ret = ret && wr.getCachedLastError().ok();
        }//w w  w.j a  v  a  2s .  co m
    }
    return ret;
}

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

License:Open Source License

private static void copyDB(final String from_host, final String to_host, final String from_db,
        final String to_db, final String from_port, final String to_port, final boolean appendCollections,
        final boolean displayAllIds) throws UnknownHostException, IOException {
    assert from_host != null;
    assert to_host != null;
    assert from_db != null;
    assert to_db != null;
    assert from_port != null;
    assert to_port != null;

    final int MAX_LOOP_SIZE = 15000; // MongoException$CursorNotFound
    final MongoClient fromClient = new MongoClient(from_host, Integer.parseInt(from_port));
    final MongoClient toClient = new MongoClient(to_host, Integer.parseInt(to_port));
    final DB fromDb = fromClient.getDB(from_db);
    final DB toDb = toClient.getDB(to_db);

    if (!appendCollections) {
        toDb.dropDatabase();/*from   ww  w .j  a va2s  .  c  o m*/
    }

    final Set<String> colls = fromDb.getCollectionNames();

    for (String cname : colls) {
        if (cname.equals("system.indexes")) {
            continue;
        }

        final DBCollection fromColl = fromDb.getCollection(cname);
        final DBCollection toColl = toDb.getCollection(cname);

        DBCursor cursor = fromColl.find();
        int curr = 0;

        System.out.println("Copying collection: " + cname);

        while (cursor.hasNext()) {
            if (curr % MAX_LOOP_SIZE == 0) {
                if (curr > 0) {
                    cursor.close();
                    cursor = fromColl.find().skip(curr);
                    if (!cursor.hasNext()) {
                        throw new IOException("hasNext() failed");
                    }
                }
            }
            final DBObject doc = cursor.next();
            final WriteResult ret = toColl.save(doc, WriteConcern.ACKNOWLEDGED);

            if (!ret.getCachedLastError().ok()) {
                System.err.println("write error doc id=" + doc.get("_id"));
            }
            if (++curr % 1000 == 0) {
                System.out.println("+++" + curr);
            }
            if (displayAllIds) {
                System.out.println(" id=" + doc.get("_id"));
            }
        }
        cursor.close();

        System.out.println();
    }
}

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

License:Open Source License

public static Set<String> getCenters(final DBCollection coll) {
    if (coll == null) {
        throw new NullPointerException("coll");
    }/*w  ww  .  java 2  s.c o  m*/
    final Set<String> set = new TreeSet<String>();
    final DBCursor cursor = coll.find();

    while (cursor.hasNext()) {
        final BasicDBList lst = (BasicDBList) cursor.next().get(CENTER_FIELD);
        set.add((String) lst.get(0));
    }
    cursor.close();

    return set;
}

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

License:Open Source License

public static void fixMissingHttp(final DBCollection coll, final DBCollection hcoll) throws IOException {
    if (coll == null) {
        throw new NullPointerException("coll");
    }/* ww w.  jav  a  2  s  . c  o  m*/
    if (hcoll == null) {
        throw new NullPointerException("hcoll");
    }
    final String HTTP = "http://";
    final DBCursor cursor = coll.find();

    while (cursor.hasNext()) {
        final DBObject dbo = cursor.next();
        final String url = ((String) dbo.get(BROKEN_URL_FIELD)).trim();

        if (!url.startsWith(HTTP)) {
            final String fixedUrl = HTTP + url;
            final String id = (String) dbo.get(ID_FIELD);

            if (!CheckUrl.isBroken(CheckUrl.check(fixedUrl))) {
                if (!Tools.isDomain(fixedUrl)) {
                    if (!updateDocument(coll, hcoll, id, fixedUrl, "system", true)) {
                        throw new IOException("could not update document id=" + id);
                    }
                }
            }
        }
    }
    cursor.close();
}

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

License:Open Source License

public static void tabulate(final String host, final int port, final String user, final String password,
        final String database, final String collection, final String path) throws UnknownHostException {
    if (host == null) {
        throw new NullPointerException("host");
    }/*from   w ww  . ja  va 2  s.c  o m*/
    if (port <= 0) {
        throw new IllegalArgumentException("port <= 0");
    }
    if (collection == null) {
        throw new NullPointerException("collection");
    }
    if (path == null) {
        throw new NullPointerException("path");
    }
    final MongoClient mongoClient = new MongoClient(host, port);
    final DB db = mongoClient.getDB(database);
    if (user != null) {
        final boolean auth = db.authenticate(user, password.toCharArray());
        if (!auth) {
            throw new IllegalArgumentException("invalid user/password");
        }
    }
    final DBCollection coll = db.getCollection(collection);
    final DBCursor cursor = coll.find();
    final TreeMap<String, Integer> map1 = new TreeMap<String, Integer>();
    final TreeMap<Integer, String> map2 = new TreeMap<Integer, String>();
    final int ADD_VALUE = 99999999;
    final int size = cursor.size();

    while (cursor.hasNext()) {
        final BasicDBObject doc = (BasicDBObject) cursor.next();
        final String key = getValue(doc, path);

        if (key != null) {
            Integer val = map1.get(key);
            if (val == null) {
                val = 0;
            }
            val += 1;
            map1.put(key, val);
        }
    }
    cursor.close();
    for (Map.Entry<String, Integer> entry : map1.entrySet()) {
        map2.put(ADD_VALUE - entry.getValue(), entry.getKey());
    }

    System.out.println("Total # of docs: " + size + "\n");

    int idx = 0;
    for (Map.Entry<Integer, String> entry : map2.entrySet()) {
        final int val = ADD_VALUE - entry.getKey();
        final String percent = String.format("%.2f", ((float) val / size) * 100);
        System.out.println((++idx) + ") " + entry.getValue() + ": " + val + " (" + percent + "%)");
    }
}

From source file:br.bireme.tmp.AddPrettyField.java

License:Open Source License

private static void add(final String mongo_host, final int mongo_port, final String mongo_db,
        final String mongo_col) throws UnknownHostException {
    assert mongo_host != null;
    assert mongo_port > 0;
    assert mongo_db != null;
    assert mongo_col != null;

    final MongoClient client = new MongoClient(mongo_host, mongo_port);
    final DB db = client.getDB(mongo_db);
    final DBCollection coll = db.getCollection(HISTORY_COL);
    final DBCursor cursor = coll.find();
    int total = 0;

    System.out.println("host=" + mongo_host);
    System.out.println("port=" + mongo_port);
    System.out.println("database=" + mongo_db);
    System.out.println("collection=" + mongo_col);
    System.out.println("num of documents=" + cursor.size());

    while (cursor.hasNext()) {
        final BasicDBObject doc1 = (BasicDBObject) cursor.next();
        final BasicDBList list = (BasicDBList) doc1.get(ELEM_LST_FIELD);

        for (Object obj : list) {
            final BasicDBObject doc2 = (BasicDBObject) obj;
            if (!doc2.containsField(PRETTY_BROKEN_URL_FIELD)) {
                final String burl = doc2.getString(BROKEN_URL_FIELD);
                try {
                    final String pburl = EncDecUrl.decodeUrl(burl);
                    doc2.append(PRETTY_BROKEN_URL_FIELD, pburl);

                    final WriteResult wr = coll.save(doc1, WriteConcern.ACKNOWLEDGED);
                    if (wr.getCachedLastError().ok()) {
                        total++;//from  w  w w .  ja v a 2  s .  c  o m
                    } else {
                        System.err.println("Document[" + doc1.getString("_id") + "] update error.");
                    }
                } catch (IOException ioe) {
                    System.err.println("Document[" + doc1.getString("_id") + "] bad encode conversion"
                            + " url=[" + burl + "]");
                }
            }
        }
    }
    cursor.close();
    System.out.println("num of added fields: " + total);
}

From source file:br.com.teste.mongo.MongoTeste.java

public void buscar(String termo) {
    DB db = connect();//from w  ww .ja v  a 2 s. c  o  m
    DBCollection collection = db.getCollection(termo);
    DBCursor cursor = collection.find();
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }
}

From source file:br.ufabc.impress.mongo.manager.DBHelper.java

@Override
public List<Boolean> modifyNotOveride(String tableName, String json, String _id) {
    if (tableName == null || tableName.equals("") || json == null || json.equals("") || _id == null
            || _id.equals("")) {
        return null;
    }/*from  ww w.j av a 2s . co m*/
    List<Boolean> resList = new ArrayList();
    DBCollection table = db.getCollection(tableName);
    DBCursor cursor = table.find();
    while (cursor.hasNext()) {
        DBObject updateDocument = cursor.next();
        DBObject searchQuery = cursor.next();
        DBObject dbObject = (DBObject) JSON.parse(json);
        updateDocument.putAll(dbObject.toMap());
        updateDocument.removeField("_id");
        WriteResult result = table.update(searchQuery, updateDocument);
        resList.add(result.isUpdateOfExisting());
    }
    return resList;
}