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(final DBObject query) 

Source Link

Document

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

Usage

From source file:com.ciphertool.sherlock.dao.NGramDao.java

License:Open Source License

/**
 * Returns a list of top N NGrams. We have to use the low-level MongoDB API because otherwise the query takes
 * forever due to the limitation of Spring Data not providing cursor functionality.
 *///from   w w  w.j  a v  a 2  s  . c o  m
public List<NGram> findTopMostFrequentByNumWords(int numWordsQueryParam, int top) {
    DBCollection collection = mongoOperations.getCollection(DatabaseConstants.NGRAM_COLLECTION);

    DBCursor cursor;

    if (top > 0) {
        cursor = collection.find(new BasicDBObject("numWords", numWordsQueryParam))
                .sort(new BasicDBObject("frequencyWeight", -1)).limit(top);
    } else {
        cursor = collection.find(new BasicDBObject("numWords", numWordsQueryParam))
                .sort(new BasicDBObject("frequencyWeight", -1));
    }

    List<NGram> results = new ArrayList<NGram>();
    while (cursor.hasNext()) {
        DBObject next = cursor.next();

        String nGram = (String) next.get("nGram");
        Integer numWords = (Integer) next.get("numWords");
        Long frequencyWeight = (Long) next.get("frequencyWeight");

        results.add(new NGram(nGram, numWords, frequencyWeight));
    }

    return results;
}

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

License:GNU General Public License

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

    log.trace("doPost()");

    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);/*from   ww  w. ja v  a  2  s. com*/
        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.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);//from   w  w w  .ja  v a  2 s.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) {
        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 doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doPost()");

    if (!can_write(req)) {
        res.sendError(SC_UNAUTHORIZED);// w w  w. 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;
        }
    }

    boolean upsert = Boolean.parseBoolean(req.getParameter("upsert"));
    boolean multi = Boolean.parseBoolean(req.getParameter("multi"));

    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, o = null;
    try {

        r = new BufferedReader(new InputStreamReader(is));
        String q_s = r.readLine();
        if (q_s == null) {
            error(res, SC_BAD_REQUEST, Status.get("no data"));
            return;
        }
        String o_s = r.readLine();
        if (o_s == null) {
            error(res, SC_BAD_REQUEST, Status.get("obj to update missing"));
            return;
        }
        try {
            q = (DBObject) JSON.parse(q_s);
            o = (DBObject) JSON.parse(o_s);
        } 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) {

        String fn = col.getFullName();
        DBCursor c = col.find(q);
        int cnt = c.count();
        if (!multi)
            c.limit(1);
        long l = multi ? cnt : 1;
        String toupdate[] = new String[(int) l];
        int n = 0;
        boolean insert = false;

        if (upsert && !multi && cnt == 0)
            insert = true;

        while (c.hasNext()) {

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

        }
        c.close();

        List<String> flds = Config.search_index_fields.get(fn);
        boolean commit = false;
        Document doc = null;
        Search _writer = search.get_writer();
        if (flds != null && flds.size() > 0) {
            doc = new Document();
            try {
                for (String fld : flds) {
                    String val = (String) o.get(fld);
                    if (val == null)
                        continue;
                    _writer.add_searchable_s(doc, fld, val);
                    commit = true;
                }
                if (commit)
                    _writer.commit(doc);
            } catch (ClassCastException e) {
                error(res, SC_BAD_REQUEST, Status.get("searchable fields must be type String"));
                return;
            } catch (CorruptIndexException e) {
                error(res, SC_BAD_REQUEST, Status.get("Search corrupt index" + e));
                return;
            }
        }
        if (commit && insert)
            log.warn("upsert with search not implemented yet");
        else
            _writer.update(toupdate, doc);

    }

    WriteResult wr = col.update(q, o, upsert, multi, 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_CREATED);

}

From source file:com.damanzano.mongohw2_2.MongoHW2_2.java

public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient();
    DB db = client.getDB("students");
    DBCollection collection = db.getCollection("grades");

    DBCursor allGrades = collection.find(new BasicDBObject("type", "homework"))
            .sort(new BasicDBObject("student_id", 1).append("score", 1));
    try {//from ww w .jav  a2 s  . c o  m
        String studentId = "";
        while (allGrades.hasNext()) {
            DBObject grade = allGrades.next();
            System.out.println(grade);
            if (!studentId.equalsIgnoreCase(((Integer) grade.get("student_id")).toString())) {
                System.out.println("Deleting grade " + grade.get("_id").toString() + " for student "
                        + grade.get("student_id").toString());
                collection.remove(grade);
            }
            studentId = ((Integer) grade.get("student_id")).toString();
        }
    } finally {
        allGrades.close();
    }
}

From source file:com.daprota.m2.manager.MongoManager.java

License:Apache License

/**
 * Retrieves user via spceified userName.
 *
 * @param userName A user's userName.//w w w .  j  a  v  a2  s  .c o  m
* @return user if exists. Otherwise returns null.
 */
public User findUserByUserName(String userName) throws MongoException {
    DBCursor dbCur = null;

    try {
        // get a user collection
        DBCollection coll = _db.getCollection("user");
        DBObject query = new BasicDBObject("userName", userName);
        dbCur = coll.find(query);
        boolean hasNext;
        try {
            logger.debug("Call dbCur.hasNext().");
            hasNext = dbCur.hasNext();
        } catch (MongoException ex) {
            logger.error("Search for user {} failed.\n" + ex.toString(), userName);
            throw new MongoException("Search for user " + userName + " failed.");
        }
        if (hasNext) {
            DBObject user = dbCur.next();
            ArrayList<BasicDBObject> roles = (ArrayList<BasicDBObject>) user.get("roles");
            ArrayList<Role> roles2 = new ArrayList<Role>();
            if (roles != null) {
                for (BasicDBObject role : roles) {
                    Role role3 = new Role(role.get("_id").toString(), (String) role.get("name"),
                            (String) role.get("description"));
                    roles2.add(role3);
                }
                logger.debug("User {} roles added.", userName);
            }
            return (new User(user.get("_id").toString(), (String) user.get("userName"),
                    (String) user.get("password"), roles2));
        } else {
            logger.warn("User {} could not be found", userName);
            return null;
        }
    } catch (MongoException ex) {
        logger.error("Search for user {} failed.\n" + ex.toString(), userName);
        throw new MongoException("Search for user " + userName + " failed.");
    } finally {
        dbCur.close();
    }
}

From source file:com.data.DAO.MetodoPagoDAO.java

public static ArrayList consultarRecibo(Integer idMetodoPago) {
    ArrayList reciboConsulta = new ArrayList();
    try {//from   w  w w.jav a  2s . c  o m
        // To connect to mongo dbserver
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // Now connect to your databases
        DB db = mongoClient.getDB("hoex");
        System.out.println("Connect to database successfully");

        // Use an especific collection
        DBCollection coll = db.getCollection("Metodo_pago");
        System.out.println("Collection Metodo_pago selected successfully");

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

        DBCursor cursor = coll.find(whereQuery);

        while (cursor.hasNext()) {
            DBObject consultDocument = cursor.next();
            reciboConsulta.add(consultDocument.get("descripcion"));
            reciboConsulta.add(consultDocument.get("cuotas"));
            reciboConsulta.add(consultDocument.get("precio"));
            reciboConsulta.add(consultDocument.get("idReserva"));
        }
        System.out.println("Document consulted successfully");
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
    if (!reciboConsulta.isEmpty()) {
        return reciboConsulta;
    } else {
        return null;
    }
}

From source file:com.data.DAO.MetodoPagoDAO.java

public static String actualizarRecibo(Integer idMetodoPago, String descripcion, Integer cuotas, float precio,
        Integer idReserva) {//ww  w.  ja  va 2 s  .c o m
    String reciboActualizar = null;
    try {
        // To connect to mongo dbserver
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // Now connect to your databases
        DB db = mongoClient.getDB("hoex");
        System.out.println("Connect to database successfully");

        DBCollection coll = db.getCollection("Metodo_pago");
        System.out.println("Collection Metodo_pago selected successfully");

        BasicDBObject whereQuery = new BasicDBObject();
        whereQuery.put("idMetodoPago", idMetodoPago);

        DBCursor cursor = coll.find(whereQuery);

        while (cursor.hasNext()) {
            DBObject updateDocument = cursor.next();
            updateDocument.put("descripcion", descripcion);
            updateDocument.put("cuotas", cuotas);
            updateDocument.put("precio", precio);
            updateDocument.put("idReserva", idReserva);
            coll.update(whereQuery, updateDocument);
        }
        System.out.println("Document updated successfully");
        reciboActualizar = "Success";
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
    if (reciboActualizar != null) {
        return "El recibo se ha actualizado correctamente!";
    } else {
        return "El recibo no se ha actualizado!";
    }
}

From source file:com.data.DAO.MetodoPagoDAO.java

public static String borrarRecibo(Integer idMetodoPago) {
    String reciboBorrar = null;/*from  w  w  w.j  av a2  s .c  o  m*/
    try {
        // To connect to mongo dbserver
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // Now connect to your databases
        DB db = mongoClient.getDB("hoex");
        System.out.println("Connect to database successfully");

        DBCollection coll = db.getCollection("Metodo_pago");
        System.out.println("Collection Metodo_pago selected successfully");

        BasicDBObject whereQuery = new BasicDBObject();
        whereQuery.put("idMetodoPago", idMetodoPago);

        DBCursor cursor = coll.find(whereQuery);

        coll.remove(whereQuery);
        System.out.println("Documento elminado exitosamente");
        reciboBorrar = "Success";
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }

    if (reciboBorrar != null) {
        return "El recibo ha sido borrado exitosamente!";
    } else {
        return "El recibo no ha sido borrado!";
    }
}

From source file:com.deliveronthego.CommonAPI.java

@POST
@Path("/findDrivers")
@Consumes(MediaType.APPLICATION_JSON)//from www .  j ava  2s  . c  o  m
@Produces(MediaType.APPLICATION_JSON)
public Response doDeliveryDetails(String deliver) {
    System.out.println("inside delivery details");

    String message;
    GraphTraversal g = new GraphTraversal();
    try {
        System.out.println("inside delivery details");
        JSONObject deliverJson = new JSONObject(deliver);
        boolean var = new DbConnection().deliver(deliverJson.getString("emailId"),
                Double.valueOf(deliverJson.getString("pickupLatitude")),
                Double.valueOf(deliverJson.getString("pickupLongitude")),
                Double.valueOf(deliverJson.getString("dropOffLatitude")),
                Double.valueOf(deliverJson.getString("dropOffLongitude")), deliverJson.getInt("length"),
                deliverJson.getInt("breadth"), deliverJson.getInt("width"));
        System.out.println("after delivery details");

        if (var) {
            System.out.println("in success");
            message = "Delivery Details Inserted successfully";
            JSONObject statusMessage = new JSONObject();
            statusMessage.put("message", message);
            String res = g.findDriver(deliverJson.getString("emailId"), deliverJson.getDouble("pickupLatitude"),
                    deliverJson.getDouble("pickupLongitude"), deliverJson.getDouble("dropOffLatitude"),
                    deliverJson.getDouble("dropOffLongitude"));
            System.out.println(res);
            JSONArray jarr = new JSONArray(res);
            for (int j = 0; j < jarr.length(); j++) {
                JSONObject json = new JSONObject(jarr.get(j).toString());
                String driverId = json.get("driverId").toString();
                System.out.println(driverId);
                mongoclient = getConnection();
                DB db = mongoclient.getDB("deliveronthego");
                DBCollection driverSourceDetails = db.getCollection("login");
                BasicDBObject whereQuery = new BasicDBObject();
                whereQuery.put("emailId", driverId);
                whereQuery.put("userType", "Driver");
                DBCursor cursor = driverSourceDetails.find(whereQuery);
                if (cursor.hasNext()) {
                    BasicDBObject obj = (BasicDBObject) cursor.next();
                    String regId = obj.getString("regId");
                    String[] gcmIds = regId.split("\\=");
                    System.out.println(gcmIds[1]);
                    String apiKey = "AIzaSyDzXEIMFY3EGbJ4mjc9xBYyeakjggxuTC0";
                    Content content = createContent(gcmIds[1], deliverJson.getString("emailId"));

                    DotgGCMPost.post(apiKey, content);
                    DBCollection selection = db.getCollection("selection");
                    BasicDBObject sel = new BasicDBObject()
                            .append("userEmailId", deliverJson.getString("emailId"))
                            .append("driverEmailId", driverId).append("Accepted", "No");
                    selection.insert(sel);

                    throw new JSONException("gi");

                } else {
                    //System.out.println("cursor=="+cursor.toString());
                    throw new JSONException("No email found");
                }
            }
            return Response.status(200).entity(statusMessage).build();
        } else {
            System.out.println("in fail");

            message = "Delivery Details Insertion Failed";
            JSONObject statusMessage = new JSONObject();
            statusMessage.put("message", message);
            return Response.status(404).entity(statusMessage).build();
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    message = "Delivery Details Insertion Failed";
    return Response.status(404).entity(message).build();
}