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:BusinessLogic.Service.RestaurantService.java

public String getAll() {
    String response = "";
    try {/*from  w  w  w  .  j av a2  s  . c o  m*/

        ArrayList userConsult = new ArrayList();
        MongoConnection dbSingleton = MongoConnection.getInstance();

        DB db = dbSingleton.getTestdb();

        // get list of collections
        Set<String> collections = db.getCollectionNames();

        // get a single collection
        DBCollection collection = db.getCollection(collName);
        DBCursor cursor = collection.find();
        try {
            while (cursor.hasNext()) {
                response = response + cursor.next().toString() + "\n";
            }
        } finally {
            cursor.close();
        }

        System.out.println("Done");

    } catch (MongoException e) {
        e.printStackTrace();
    }
    return response;
}

From source file:CapaDato.Conexion.java

public static void main(String[] Args) throws UnknownHostException {
    try {/*from  w w  w  . j a va  2s  . c  om*/
        // Para conectarse al servidor MongoDB
        MongoClient conexion = new MongoClient("localhost", 27017);
        // Ahora conectarse a bases de datos
        DB ejemplo = conexion.getDB("Ejemplo");
        System.out.println("Conectarse a la base de datos exitoso");
        DBCollection coleccion = ejemplo.getCollection("Alumno");
        //             Set<String> collectionNames = ejemplo.getCollectionNames();
        //            for (final String s : collectionNames) 
        //            {
        //            System.out.println(s);
        //            }
        //Para consultar otro mtodo
        Object objeto = new Object();
        objeto = "null,{nombre:1}";
        DBCursor cursor = coleccion.find();

        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }

        //DBObject doc = coleccion.findOne();

        //Para consultar
        //DBCursor cursor = coleccion.find ();
        //System.out.println(cursor);
        //            int i = 1;
        //          while (cursor.hasNext ()) 
        //          { 
        //             System.out.println ("insertado documento:" + i); 
        //             System.out.println (cursor.next ()); 
        //             i ++;
        //          }

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

}

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   www.  j  a va2s. c  o 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 doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.fine("doGet()");

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

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

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

    DBCursor c = col.find();
    if (c == null || c.count() == 0) {
        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();
        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);

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

}

From source file:com.apifest.oauth20.MongoDBManager.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public List<Scope> getAllScopes() {
    List<Scope> list = new ArrayList<Scope>();
    DBCollection coll = db.getCollection(SCOPE_COLLECTION_NAME);
    List<DBObject> result = coll.find().toArray();
    for (DBObject obj : result) {
        Map<String, Object> mapLoaded = obj.toMap();
        Scope scope = Scope.loadFromMap(mapLoaded);
        list.add(scope);//from w w  w. java 2 s . c  om
    }
    return list;
}

From source file:com.apifest.oauth20.MongoDBManager.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public List<ApplicationInfo> getAllApplications() {
    List<ApplicationInfo> list = new ArrayList<ApplicationInfo>();
    DBCollection coll = db.getCollection(CLIENTS_COLLECTION_NAME);
    List<DBObject> result = coll.find().toArray();
    for (DBObject obj : result) {
        BSONObject bson = obj;//from  w ww . j  a v  a2s  .c o m
        Map<String, Object> mapLoaded = bson.toMap();
        ApplicationInfo loadedCreds = ApplicationInfo.loadFromMap(mapLoaded);
        list.add(loadedCreds);
    }
    return list;
}

From source file:com.apifest.oauth20.persistence.mongodb.MongoDBManager.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public List<ClientCredentials> getAllApplications() {
    List<ClientCredentials> list = new ArrayList<ClientCredentials>();
    DBCollection coll = db.getCollection(CLIENTS_COLLECTION_NAME);
    List<DBObject> result = coll.find().toArray();
    for (DBObject obj : result) {
        Map<String, Object> mapLoaded = obj.toMap();
        ClientCredentials loadedCreds = ClientCredentials.loadFromMap(mapLoaded);
        list.add(loadedCreds);/*from  w  w w .  java2  s . c o  m*/
    }
    return list;
}

From source file:com.app.mongoDao.MongoBookDao.java

@Override
public List<Book> listBook() {
    ArrayList<Book> booklist = new ArrayList<>();
    try {/* w ww .j  a v  a  2s.c  om*/
        DBCollection data = DatabaseConfig.configure();
        BasicDBObject orderBy = new BasicDBObject("id", 1);
        DBCursor docs = data.find().sort(orderBy);

        while (docs.hasNext()) {
            DBObject doc = docs.next();
            Book librarybook = new Book(doc.get("bookname").toString(), doc.get("author").toString());
            booklist.add(librarybook);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return booklist;
}

From source file:com.aw.util.MongoDbUtil.java

public static Object findMaxValueForKey(String collection, String key) {
    DBCollection table = getCollection(defaultDBName, collection);
    BasicDBObject query = new BasicDBObject();
    query.put(key, -1);//from  w w w  .j a  v  a 2 s  . c om
    DBCursor cursor = table.find().sort(query).limit(1);
    Object value = null;
    while (cursor.hasNext()) {
        DBObject object = cursor.next();
        value = object.get(key);
    }
    return value;
}

From source file:com.ayu.filter.DbListner.java

License:Open Source License

/**
  * @see ServletContextListener#contextInitialized(ServletContextEvent)
  *//* ww  w.  j a  v  a  2  s .  c  o  m*/
public void contextInitialized(ServletContextEvent arg0) {
    MongoClient mongoClient = null;
    try {
        mongoClient = new MongoClient();
    } catch (UnknownHostException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    DB db = mongoClient.getDB("test");
    DBCollection coll;
    coll = db.getCollection("test");
    DBCursor cursor = coll.find();
    while (cursor.hasNext()) {
        String ip = (String) cursor.next().get("Ip-Address");
        if (arg0.getServletContext().getAttribute(ip) == null) {
            arg0.getServletContext().setAttribute(ip, ip);
        }
    }

}