Example usage for com.mongodb DBCursor count

List of usage examples for com.mongodb DBCursor count

Introduction

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

Prototype

public int count() 

Source Link

Document

Counts the number of objects matching the query.

Usage

From source file:backend.facades.UserController.java

public boolean checkEmail(String email) {
    boolean retValue = false;
    BasicDBObject query = new BasicDBObject();
    query.put("email", email);
    DBCursor cursor = userCollection.find(query);
    try {//from w  ww.  j  a va2s  .c  o  m
        if (cursor == null) {
            return false;
        }
        if (cursor != null && cursor.count() > 0) {
            retValue = true;
        } else {
            return false;
        }
    } finally {
        cursor.close();
    }
    return retValue;
}

From source file:backend.facades.UserController.java

public boolean checkUsername(String username) {
    boolean retValue = false;
    BasicDBObject query = new BasicDBObject();
    query.put("username", username);
    DBCursor cursor = userCollection.find(query);

    try {//from   w  w  w  . j ava  2  s . co m
        if (cursor != null && cursor.count() > 0) {
            retValue = true;
        }
    } finally {
        cursor.close();
    }
    return retValue;
}

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

License:Open Source License

public static SearchResult getDocuments(final DBCollection coll, final String docMast, final String docId,
        final String docUrl, final Set<String> centerIds, final boolean decreasingOrder, final int from,
        final int count) {
    if (coll == null) {
        throw new NullPointerException("coll");
    }/*from ww w .  j  a v  a 2  s .c  o  m*/
    if (from < 1) {
        throw new IllegalArgumentException("from[" + from + "] < 1");
    }
    if (count < 1) {
        throw new IllegalArgumentException("count[" + count + "] < 1");
    }
    final List<IdUrl> lst = new ArrayList<IdUrl>();
    final BasicDBObject query = new BasicDBObject();

    if (docMast != null) {
        query.append(MST_FIELD, docMast);
    }
    if (docId != null) {
        final Pattern pat = Pattern.compile("^" + docId.trim() + "_\\d+");
        query.append(ID_FIELD, pat);
    }
    if (docUrl != null) {
        query.append(BROKEN_URL_FIELD, docUrl.trim());
    }
    if (centerIds != null) {
        final BasicDBList cclst = new BasicDBList();
        for (String centerId : centerIds) {
            cclst.add(centerId);
        }
        final BasicDBObject in = new BasicDBObject("$in", cclst);
        query.append(CENTER_FIELD, in);
    }
    final BasicDBObject sort = new BasicDBObject(DATE_FIELD, decreasingOrder ? -1 : 1);
    final DBCursor cursor = coll.find(query).sort(sort).skip(from - 1).limit(count);
    final int size = cursor.count();
    final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    while (cursor.hasNext()) {
        final DBObject doc = cursor.next();
        final BasicDBList ccsLst = (BasicDBList) doc.get(CENTER_FIELD);
        final Set<String> ccs = new TreeSet<String>();

        for (Object cc : ccsLst) {
            ccs.add((String) cc);
        }
        final IdUrl iu = new IdUrl((String) doc.get(ID_FIELD), (String) doc.get(PRETTY_BROKEN_URL_FIELD), ccs,
                format.format((Date) (doc.get(DATE_FIELD))), (String) doc.get(MST_FIELD));
        lst.add(iu);
    }
    cursor.close();

    return new SearchResult(size, lst);
}

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

License:Open Source License

public static SearchResult2 getHistoryDocuments(final DBCollection coll, final Element elem, final int from,
        final int count) throws IOException, ParseException {
    if (coll == null) {
        throw new NullPointerException("coll");
    }//w  ww  . jav  a  2  s  . c  o m
    if (elem == null) {
        throw new NullPointerException("elem");
    }
    if (from < 1) {
        throw new IllegalArgumentException("from[" + from + "] < 1");
    }
    if (count < 1) {
        throw new IllegalArgumentException("count[" + count + "] < 1");
    }
    final List<Element> lst = new ArrayList<Element>();
    final BasicDBObject query = new BasicDBObject();
    final String root = ELEM_LST_FIELD + ".0.";
    final String updated = root + LAST_UPDATE_FIELD;

    if (elem.getDbase() != null) {
        query.append(MST_FIELD, elem.getDbase().trim());
    }
    if (elem.getId() != null) {
        final Pattern pat = Pattern.compile("^" + elem.getId().trim() + "_\\d+");
        query.append(ID_FIELD, pat);
    }
    if (elem.getFurl() != null) {
        query.append(root + FIXED_URL_FIELD, elem.getFurl().trim());
    }
    if (!elem.getCcs().isEmpty()) {
        final BasicDBList cclst = new BasicDBList();
        for (String centerId : elem.getCcs()) {
            cclst.add(centerId.trim());
        }
        final String cc = root + CENTER_FIELD;
        final BasicDBObject in = new BasicDBObject("$in", cclst);
        query.append(cc, in);
    }
    if (elem.getDate() != null) {
        final SimpleDateFormat simple = new SimpleDateFormat("dd-MM-yyyy");
        final Date date = simple.parse(elem.getDate().trim());
        final BasicDBObject qdate = new BasicDBObject("$gte", date);
        query.append(updated, qdate);
    }
    if (elem.getUser() != null) {
        final String user = root + USER_FIELD;
        query.append(user, elem.getUser().trim());
    }

    final BasicDBObject sort = new BasicDBObject(updated, -1);
    final DBCursor cursor = coll.find(query).sort(sort).skip(from - 1).limit(count);
    final int size = cursor.count();
    final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

    while (cursor.hasNext()) {
        final BasicDBObject hdoc = (BasicDBObject) cursor.next();
        final BasicDBList elst = (BasicDBList) hdoc.get(ELEM_LST_FIELD);
        final BasicDBObject hcurdoc = (BasicDBObject) elst.get(0);
        if (hcurdoc == null) {
            throw new IOException("document last element found.");
        }
        final BasicDBList ccLst = (BasicDBList) hcurdoc.get(CENTER_FIELD);
        final List<String> ccs = Arrays.asList(ccLst.toArray(new String[0]));
        final Element elem2 = new Element(hdoc.getString(ID_FIELD), hcurdoc.getString(BROKEN_URL_FIELD),
                hcurdoc.getString(PRETTY_BROKEN_URL_FIELD), hcurdoc.getString(FIXED_URL_FIELD),
                hdoc.getString(MST_FIELD), format.format((Date) (hcurdoc.get(LAST_UPDATE_FIELD))),
                hcurdoc.getString(USER_FIELD), ccs, hcurdoc.getBoolean(EXPORTED_FIELD));
        lst.add(elem2);
    }
    cursor.close();

    return new SearchResult2(size, lst.size(), lst);
}

From source file:calliope.db.MongoConnection.java

License:Open Source License

/**
 * List all the documents in a Mongo collection
 * @param collName the name of the collection
 * @return a String array of document keys
 * @throws AeseException // w ww . j ava2  s.  co m
 */
@Override
public String[] listCollection(String collName) throws AeseException {
    if (!collName.equals(Database.CORPIX)) {
        try {
            connect();
        } catch (Exception e) {
            throw new AeseException(e);
        }
        DBCollection coll = getCollectionFromName(collName);
        BasicDBObject keys = new BasicDBObject();
        keys.put(JSONKeys.DOCID, 1);
        DBCursor cursor = coll.find(new BasicDBObject(), keys);
        System.out.println("Found " + cursor.count() + " documents");
        cursor.count();
        if (cursor.length() > 0) {
            String[] docs = new String[cursor.length()];
            Iterator<DBObject> iter = cursor.iterator();
            int i = 0;
            while (iter.hasNext())
                docs[i++] = (String) iter.next().get(JSONKeys.DOCID);
            return docs;
        } else {
            return new String[0];
        }
    } else {
        GridFS gfs = new GridFS(db, collName);
        DBCursor curs = gfs.getFileList();
        int i = 0;
        List<DBObject> list = curs.toArray();
        HashSet<String> set = new HashSet<String>();
        Iterator<DBObject> iter = list.iterator();
        while (iter.hasNext()) {
            String name = (String) iter.next().get("filename");
            set.add(name);
        }
        String[] docs = new String[set.size()];
        set.toArray(docs);
        return docs;
    }
}

From source file:cl.wsconsulta.consulta.Consulta.java

@WebMethod(operationName = "consultar")
public String realizarConsulta(@WebParam(name = "consulta") BasicDBList privileges) throws IOException {
    DB database;/*from   w ww  .jav  a 2  s  . c o m*/
    try (BufferedReader entrada = new BufferedReader(new FileReader("datos.ini"))) {
        database = null;
        try {
            dataBase = entrada.readLine();
            indiceInvertido = entrada.readLine();
            coleccionDocumentos = entrada.readLine();
            coleccionIndice = entrada.readLine();

            MongoClient mongoClient = new MongoClient();
            database = mongoClient.getDB(dataBase);

        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }
        entrada.close();
    }

    DBCollection indiceInvertido = database.getCollection(coleccionIndice);
    DBCollection documento = database.getCollection(coleccionDocumentos);

    while (true) {

        BufferedReader lector = new BufferedReader(new InputStreamReader(System.in));
        String consulta = lector.readLine().toUpperCase();
        BasicDBObject query = new BasicDBObject("palabra", consulta);
        DBCursor cursor = indiceInvertido.find(query);
        if (cursor.count() == 0) {
            System.out.println("Busqueda sin resultados: " + consulta);
        } else {
            while (cursor.hasNext()) {
                privileges = (BasicDBList) cursor.next().get("documento");
                //DBObject obj = cursor.next();
                //Object value = obj.get("documento");
                //System.out.println(value);
            }
            System.out.println(privileges);
        }
    }

}

From source file:cl.wsconsulta.servlet.ConsultaServlet.java

public static String consultar(String consulta) throws FileNotFoundException, IOException {

    DB database;//from www  . jav a 2s . c  o  m

    database = null;

    dataBase = "labsd";
    indiceInvertido = "prueba.xml";
    coleccionDocumentos = "documentos";
    coleccionIndice = "indiceInvertido";

    MongoClient mongoClient = new MongoClient();
    database = mongoClient.getDB(dataBase);

    DBCollection indiceInvertido = database.getCollection(coleccionIndice);
    DBCollection documento = database.getCollection(coleccionDocumentos);
    BasicDBList privileges = new BasicDBList();

    BasicDBObject query = new BasicDBObject("palabra", consulta);
    DBCursor cursor = indiceInvertido.find(query);
    if (cursor.count() == 0) {
        System.out.println("Busqueda sin resultados: " + consulta);
    } else {
        while (cursor.hasNext()) {

            privileges = (BasicDBList) cursor.next().get("documento");

            //DBObject obj = cursor.next();
            //Object value = obj.get("documento");
            //System.out.println(value);
        }
    }
    String lista = privileges.toString();
    return lista;

}

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

License:GNU General Public License

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

    log.fine("doPost()");

    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);/*from www.j ava  2s  . c  om*/
        return;
    }

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        error(res, SC_BAD_REQUEST, Status.get("param name missing"));
        return;
    }
    String skip = req.getParameter("skip");
    String limit = req.getParameter("limit");

    DB db = mongo.getDB(db_name);
    DBCollection col = db.getCollection(col_name);

    BufferedReader r = null;
    DBObject q = null, sort = 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;
        }
        // sort param
        data = r.readLine();
        if (data != null) {
            try {
                sort = (DBObject) JSON.parse(data);
            } catch (JSONParseException e) {
                error(res, SC_BAD_REQUEST, Status.get("can not parse sort arg"));
                return;
            }
        }

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

    DBCursor c;
    if (sort == null)
        c = col.find(q);
    else
        c = col.find(q).sort(sort);
    if (c == null) {
        error(res, SC_NOT_FOUND, Status.get("no documents found"));
        return;
    }

    res.setIntHeader("X-Documents-Count", c.count());

    if (limit != null) {
        try {
            c.limit(Math.min(Integer.parseInt(limit), MAX_FIELDS_TO_RETURN));
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse limit"));
            c.close();
            return;
        }
    } else
        c.limit(MAX_FIELDS_TO_RETURN);

    if (skip != null) {
        try {
            c.skip(Integer.parseInt(skip));
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse skip"));
            c.close();
            return;
        }
    }

    StringBuilder buf = tl.get();
    // reset buf
    buf.setLength(0);

    int no = 0;
    buf.append("[");
    while (c.hasNext()) {

        DBObject o = c.next();
        JSON.serialize(o, buf);
        buf.append(",");
        no++;

    }

    if (no > 0)
        buf.setCharAt(buf.length() - 1, ']');
    else
        buf.append(']');

    res.setIntHeader("X-Documents-Returned", no);

    out_str(req, buf.toString(), "application/json");

}

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

License:GNU General Public License

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

    log.fine("doGet()");

    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);/*from ww w .  java  2 s .co m*/
        return;
    }

    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        error(res, SC_BAD_REQUEST, Status.get("param name missing"));
        return;
    }
    String skip = req.getParameter("skip");
    String limit = req.getParameter("limit");

    DB db = mongo.getDB(db_name);
    DBCollection col = db.getCollection(col_name);

    DBCursor c = col.find();
    if (c == null) {
        error(res, SC_NOT_FOUND, Status.get("no documents found"));
        return;
    }

    res.setIntHeader("X-Documents-Count", c.count());

    if (limit != null) {
        try {
            c.limit(Math.min(Integer.parseInt(limit), MAX_FIELDS_TO_RETURN));
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse limit"));
            c.close();
            return;
        }
    } else
        c.limit(MAX_FIELDS_TO_RETURN);

    if (skip != null) {
        try {
            c.skip(Integer.parseInt(skip));
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse skip"));
            c.close();
            return;
        }
    }

    StringBuilder buf = tl.get();
    buf.setLength(0);

    int no = 0;
    buf.append("[");
    while (c.hasNext()) {

        DBObject o = c.next();
        JSON.serialize(o, buf);
        buf.append(",");
        no++;

    }

    if (no > 0)
        buf.setCharAt(buf.length() - 1, ']');
    else
        buf.append(']');

    res.setIntHeader("X-Documents-Returned", no);

    out_str(req, buf.toString(), "application/json");

}

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

License:GNU General Public License

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

    log.fine("doPost()");

    // server auth
    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);//from ww  w .  ja  v  a  2 s.  c  o m
        return;
    }

    String ret = null;

    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;
        }
    }
    String skip = req.getParameter("skip");
    String limit = req.getParameter("limit");

    String _fields = req.getParameter("fields");
    String fields[] = null;
    if (_fields != null)
        fields = _fields.split("[,]");

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

    StringBuilder buf = tl.get();
    // reset buf
    buf.setLength(0);

    BufferedReader r = null;
    DBObject q = null, sort = 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);
            if (cache != null) {
                buf.append(db_name);
                buf.append(col_name);
                buf.append(data);
            }
        } catch (JSONParseException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
            return;
        }
        // sort param
        data = r.readLine();
        if (data != null) {
            try {
                sort = (DBObject) JSON.parse(data);
            } catch (JSONParseException e) {
                error(res, SC_BAD_REQUEST, Status.get("can not parse sort arg"));
                return;
            }
            if (cache != null)
                buf.append(data);
        }

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

    // limit
    int lim;
    if (limit != null) {
        try {
            lim = Math.min(Integer.parseInt(limit), MAX_FIELDS_TO_RETURN);
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse limit"));
            return;
        }
    } else {
        lim = MAX_FIELDS_TO_RETURN;
    }
    if (cache != null) {
        buf.append(";limit=");
        buf.append(lim);
    }

    // skip
    int sk = -1;
    if (skip != null) {
        try {
            sk = Integer.parseInt(skip);
            if (cache != null) {
                buf.append(";skip=");
                buf.append(sk);
            }
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse skip"));
            return;
        }
    }

    // fields
    if (cache != null && _fields != null) {
        buf.append(";fields=");
        buf.append(_fields);
    }

    // from cache
    String cache_key = null;
    if (cache != null) {
        cache_key = buf.toString();
        try {
            ret = (String) cache.get(cache_key);
        }
        // some wrong char in key
        catch (IllegalArgumentException e) {
            int l = buf.length();
            for (int i = 0; i < l; i++) {
                if (buf.charAt(i) == ' ')
                    buf.setCharAt(i, '*');
            }
            cache_key = buf.toString();
            ret = (String) cache.get(cache_key);
        }
        if (ret != null) {
            out_str(req, ret, "application/json");
            return;
        }
    }

    // cursor
    DBCursor c;
    if (fields != null) {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        int len = fields.length;
        for (int i = 0; i < len; i++) {
            String s = fields[i];
            sb.append('"');
            sb.append(s);
            sb.append('"');
            sb.append(":1");
            if (i != (len - 1))
                sb.append(",");
        }
        sb.append("}");
        c = col.find(q, (DBObject) JSON.parse(sb.toString()));
    } else
        c = col.find(q);

    if (c == null || c.count() == 0) {
        error(res, SC_NOT_FOUND, Status.get("no documents found"));
        return;
    }

    if (sort != null)
        c.sort(sort);

    res.setIntHeader("X-Documents-Count", c.count());

    c.limit(lim);
    if (sk != -1)
        c.skip(sk);

    // reset buf
    buf.setLength(0);

    int no = 0;
    buf.append("[");
    while (c.hasNext()) {

        DBObject o = c.next();
        if (rm_id)
            o.removeField("_id");
        JSON.serialize(o, buf);
        buf.append(",");
        no++;

    }
    c.close();

    if (no > 0)
        buf.setCharAt(buf.length() - 1, ']');
    else
        buf.append(']');

    res.setIntHeader("X-Documents-Returned", no);

    ret = buf.toString();
    if (cache != null)
        cache.set(cache_key, ret);

    out_str(req, ret, "application/json");

}