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:AllUser.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        al = new ArrayList<String>();
        // To connect to mongodb server
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // Now connect to your databases
        DB db = mongoClient.getDB("XHiring");
        System.out.println("Connect to database successfully");
        DBCollection coll = db.getCollection("users");
        System.out.println("Collection mycol selected successfully");

        DBCursor cursor = coll.find();
        int i = 1;
        try {//  w  w  w .j  a v  a2s.  c  o m
            while (cursor.hasNext()) {

                al.add(cursor.next().toString());
                i++;
            }
        } finally {
            System.out.println("arra: " + al);
            Genson obj = new Genson();
            out.println(obj.serialize(al));
        }

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

From source file:RequestHandler.java

public void retrieve(HttpServletRequest request, HttpServletResponse response) {
    DB db = mongo.getDB("test");
    DBCollection dbc = db.getCollection(collection);
    BasicDBObject add = new BasicDBObject();

    try (PrintWriter out = response.getWriter()) {
        /*TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head><script>" + "function myFunction(elt) {"
                + " elt.setAttribute('selected_object_id', elt.getAttribute('id'));"
                + "var xhr = new XMLHttpRequest();"
                + "    xhr.open('GET', 'http://localhost:8080/MongoCraig/DeleteInfo', true);"
                + "    xhr.send(null);}" + "</script></head>");
        DBCursor cursor = dbc.find();
        out.println("<body>");
        for (DBObject record : cursor) {
            out.println("<p>First Name : " + record.get("firstname") + "</p>");
            out.println("<p>Last Name : " + record.get("lastname") + "</p>");
            out.println("<p>What : " + record.get("what") + "</p>");
            out.println("<p>Price : " + record.get("price") + "</p>");
            out.println("<button id=" + record.get("_id") + " onclick='myFunction(this); '>DELETE</button> ");

        }//from w  w w . j a  v a 2 s  . c o m
        out.println("</body>");
        out.println("</html>");
    } catch (Exception e) {

    }
}

From source file:fList.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w w w.ja va  2  s. c  o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter pw = response.getWriter();
    response.setContentType("text/html");

    String username = request.getParameter("username");

    try {
        MongoClient mongo = new MongoClient("localhost", 27017);
        DB db = mongo.getDB("test");
        System.out.println("Connection established");
        DBCollection User = db.getCollection("User");

        DBCursor cursor = User.find();

        while (cursor.hasNext()) {
            DBObject result = cursor.next();
            String s = result.get("username").toString();
            if (!s.equals(username)) {
                response.getWriter().write(s);
                response.getWriter().write(" ");
            }

        }

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

From source file:filterFriends.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   www  .  j  a v a  2  s. c o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter pw = response.getWriter();
    response.setContentType("text/html");

    String username = request.getParameter("username");
    String filtered_name = request.getParameter("filtered");

    try {
        MongoClient mongo = new MongoClient("localhost", 27017);
        DB db = mongo.getDB("test");
        System.out.println("Connection established");
        DBCollection User = db.getCollection("User");

        DBCursor cursor = User.find();

        while (cursor.hasNext()) {
            DBObject result = cursor.next();
            String s = result.get("username").toString();
            if (s.equals(filtered_name)) {
                response.getWriter().write(s);
                response.getWriter().write(" ");
            }

        }

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

From source file:UnitTest3.java

License:Open Source License

public static int testgridfs() {

    long time1;/*from w w  w.  j  a  v  a  2s  .c o m*/
    long time2;
    long time3;
    long time4;

    try {

        MongoClient mongo = new MongoClient("localhost", 27017);
        DB db = mongo.getDB("JFileDB");

        // TODO JFileMetaDataTable should be in MetaDB database
        DBCollection collection = db.getCollection("JFileMetaDataTable");

        String newFileName = "com.dilmus.scabi.testdata.in.App.class";

        File jFile = new File("/home/anees/workspace/testdata/in/App.class");

        // create a JFileTable namespace
        GridFS gfsj = new GridFS(db, "JFileTable");

        // get file from local drive
        GridFSInputFile gfsFile = gfsj.createFile(jFile);

        // set a new filename for identify purpose
        gfsFile.setFilename(newFileName);
        gfsFile.setContentType("class"); // jar, zip, war
        // save the image file into mongoDB
        gfsFile.save();

        // Let's create a new JSON document with some "metadata" information
        BasicDBObject info = new BasicDBObject();
        info.put("DBHost", "localhost");
        info.put("DBPort", "27017");
        info.put("JFileName", newFileName);
        info.put("JFileID", gfsFile.getId());
        info.put("JFileMD5", gfsFile.getMD5());
        collection.insert(info, WriteConcern.ACKNOWLEDGED);

        // print the result
        DBCursor cursor = gfsj.getFileList();
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }

        DBCursor cursor2 = collection.find();

        while (cursor2.hasNext()) {
            System.out.println(cursor2.next());
        }

        // get file by it's filename
        GridFSDBFile jForOutput = gfsj.findOne(newFileName);

        // save it into a new image file
        jForOutput.writeTo("/home/anees/workspace/testdata/out/AppOut.class");

        // remove the file from mongoDB
        // gfsj.remove(gfsj.findOne(newFileName));

        System.out.println("Done");
        mongo.close();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (MongoException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return 0;
}

From source file:search.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w ww.j ava 2  s . c o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet search</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet search at " + request.getContextPath() + "</h1>");
        String srch_id = request.getParameter("search");
        DB db;

        Mongo mongo = new Mongo("LocalHost", 27017);
        db = mongo.getDB("local");
        out.println("db connected is..." + db);
        DBCollection collection = db.getCollection("StartupHun");
        out.println("table used connected is..." + collection);
        BasicDBObject query = new BasicDBObject("founded_year", new BasicDBObject("$gt", 2005));
        BasicDBObject cat = new BasicDBObject();
        //query.put("name", srch_id);
        DBCursor cursor = collection.find();
        // Print out "highest" priority items
        BasicDBObject query1 = null;
        int i = 0;
        while (cursor.hasNext()) {
            //out.println(cursor.next());
            query1 = (BasicDBObject) cursor.next();

            out.println((Integer) query1.get("founded_year") + "  " + i);
            i++;
        }

        out.println("</body>");
        out.println("</html>");
    }
}

From source file:ReadOplog.java

License:Apache License

public static void main(String[] args) throws Exception {

    MongoClient mongoClient = new MongoClient();
    DB local = mongoClient.getDB("local");

    DBCollection oplog = local.getCollection("oplog.$main");

    DBCursor lastCursor = oplog.find().sort(new BasicDBObject("$natural", -1)).limit(1);
    if (!lastCursor.hasNext()) {
        System.out.println("no oplog!");
        return;/* ww w .j a v a  2  s  .c o m*/
    }
    DBObject last = lastCursor.next();

    BSONTimestamp ts = (BSONTimestamp) last.get("ts");
    System.out.println("starting point: " + ts);

    while (true) {
        System.out.println("starting at ts: " + ts);
        DBCursor cursor = oplog.find(new BasicDBObject("ts", new BasicDBObject("$gt", ts)));
        cursor.addOption(Bytes.QUERYOPTION_TAILABLE);
        cursor.addOption(Bytes.QUERYOPTION_AWAITDATA);
        while (cursor.hasNext()) {
            DBObject x = cursor.next();
            ts = (BSONTimestamp) x.get("ts");
            System.out.println("\t" + x);
        }

        Thread.sleep(1000);
    }
}

From source file:Search_trainer.java

@Override
public void actionPerformed(ActionEvent ae) {
    // TODO Auto-generated method stub
    add(jLabel3);//from   ww w . j  a v  a2s. co  m
    add(jTextField1);
    add(jButton1);

    if (ae.getSource() == jComboBox1) {
        String Variable = jComboBox1.getSelectedItem().toString();
        jLabel3.setText("");
        jTextField1.setText("");

        if (Variable == "All_Trainers") {
            try {
                MongoClient mongo = new MongoClient("localhost", 27017);
                DB db = mongo.getDB("Gym");
                DBCollection Gym_Collection = db.getCollection("trainer");
                DBCursor cursor1 = Gym_Collection.find();
                int i = 0;
                String[][] s = new String[20][10];
                while (cursor1.hasNext()) {
                    cursor1.next();
                    s[i][0] = cursor1.curr().get("First_Name").toString();
                    s[i][1] = cursor1.curr().get("Last_Name").toString();
                    s[i][2] = cursor1.curr().get("Batch").toString();
                    s[i][3] = cursor1.curr().get("Age").toString();
                    s[i][4] = cursor1.curr().get("Username").toString();
                    s[i][5] = cursor1.curr().get("Password").toString();
                    s[i][6] = cursor1.curr().get("Phone_Number").toString();
                    s[i][7] = cursor1.curr().get("Address").toString();
                    i++;
                }

                JFrame frame = new JFrame("Resulted Trainers");
                frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
                Trainer_Table ne = new Trainer_Table(s);
                ne.setOpaque(true);
                frame.setContentPane(ne);
                frame.pack();
                frame.setVisible(true);
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            jLabel3.setFont(new java.awt.Font("SansSerif", 3, 14)); // NOI18N
            jLabel3.setForeground(new java.awt.Color(204, 255, 204));
            jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
            jLabel3.setText("Enter " + Variable + ": ");
            jLabel3.setBounds(55, 230, 200, 40);

            jTextField1.setBounds(267, 230, 200, 40);

            jButton1.setBackground(new java.awt.Color(51, 0, 51));
            jButton1.setFont(new java.awt.Font("SansSerif", 3, 12)); // NOI18N
            jButton1.setForeground(new java.awt.Color(255, 255, 255));
            jButton1.setText("Search Trainer");
            jButton1.setBounds(160, 300, 300, 40);
            setVisible(true);
        }
    } else if (ae.getSource() == jButton1) {

        try {

            String Variable = jComboBox1.getSelectedItem().toString();
            MongoClient mongo = new MongoClient("localhost", 27017);
            DB db = mongo.getDB("Gym");
            DBCollection Gym_Collection = db.getCollection("trainer");
            BasicDBObject fields;
            if (Variable == "First_Name" || Variable == "Last_Name" || Variable == "Username"
                    || Variable == "Batch") {
                fields = new BasicDBObject(Variable, jTextField1.getText().toString());
            } else {
                fields = new BasicDBObject(Variable, Integer.parseInt(jTextField1.getText().toString()));
            }
            DBCursor cursor1 = Gym_Collection.find(fields);
            int i = 0;
            String[][] s = new String[20][10];
            while (cursor1.hasNext()) {
                cursor1.next();
                s[i][0] = cursor1.curr().get("First_Name").toString();
                s[i][1] = cursor1.curr().get("Last_Name").toString();
                s[i][2] = cursor1.curr().get("Batch").toString();
                s[i][3] = cursor1.curr().get("Age").toString();
                s[i][4] = cursor1.curr().get("Username").toString();
                s[i][5] = cursor1.curr().get("Password").toString();
                s[i][6] = cursor1.curr().get("Phone_Number").toString();
                s[i][7] = cursor1.curr().get("Address").toString();
                i++;
            }

            JFrame frame = new JFrame("Resulted Trainers");
            frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            Trainer_Table ne = new Trainer_Table(s);
            ne.setOpaque(true);
            frame.setContentPane(ne);
            frame.pack();
            frame.setVisible(true);
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NumberFormatException e) {// To validate for data types
            JOptionPane.showMessageDialog(this, "Please Check the Data types");
            jTextField1.setText("");
        }
    } else if (ae.getSource() == jButton2) {
        this.setVisible(false);
        new Admin().setVisible(true);
    }
}

From source file:Slots.java

String GetSlots() {
    DBCollection coll = db.getCollection("Slots");
    DBCursor cursor = coll.find();
    String s = " ";
    int i = 0;/*  w ww .  ja  v a  2 s.com*/
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
        i = 1;
        s = s + "....." + cursor.next();

    }
    return s;

}

From source file:emp_detail_table.java

public void display_table() {
    try {/*w  ww  .  j  av  a2  s .  co m*/
        MongoClient mc = new MongoClient("localhost", 27017);
        DB db = mc.getDB("parking_system");
        DBCollection collection = db.getCollection("employee_info");

        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();

        DBCursor cursor = collection.find();

        jTable1.setShowGrid(true);
        while (cursor.hasNext()) {

            DBObject temp = cursor.next();
            model.addRow(new Object[] { temp.get("name"), temp.get("_id"), temp.get("password"),
                    temp.get("mobileno") });
        }

        //            else if(input.equalsIgnoreCase("")==true)
        //                JOptionPane.showMessageDialog(rootPane, "Error:: Enter a product name");
        //            else
        //              JOptionPane.showMessageDialog(rootPane, "Product not found");  
        //    
    } catch (UnknownHostException e) {
        e.getMessage();

    }
}