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

public void loc() {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB dbBusiness = mongoClient.getDB("business");
    DBCollection collBusiness = dbBusiness.getCollection("business");
    List<DBObject> categoryIdList = new ArrayList<DBObject>();
    DBCursor cursorForBusiness = collBusiness.find();
    while (cursorForBusiness.hasNext()) {
        categoryIdList.add(cursorForBusiness.next());
    }/*  ww  w  .jav a  2  s  .  c o m*/
    for (DBObject s : categoryIdList) {
        System.out.println(s.get("business_id").toString());
        System.out.println(s.get("longitude").toString());
        System.out.println(s.get("latitude").toString());

        BasicDBObject newDocument = new BasicDBObject();
        BasicDBList addFields = new BasicDBList();
        addFields.add(s.get("longitude").toString());
        addFields.add(s.get("latitude").toString());
        newDocument.append("$set", new BasicDBObject().append("loc", addFields));

        BasicDBObject searchQuery = new BasicDBObject().append("business_id", s.get("business_id").toString());

        collBusiness.update(searchQuery, newDocument);
    }

}

From source file:gMIRC_server.java

public static void cleaner() {
    try {/*w  w  w  .  ja  v a 2  s  . c  o m*/
        boolean hard_clean = false;
        MongoClient mongoClient = new MongoClient();
        DB db = mongoClient.getDB("mirc");
        DBCollection coll = db.getCollection("activeUser");

        DBCursor cursor = coll.find();
        try {
            Date now = new Date();
            long timestamp_now = now.getTime();
            long treshold = timestamp_now - (1000 * 60 * 5); //5 minutes
            while (cursor.hasNext()) {
                hard_clean = true;
                BasicDBObject temp = (BasicDBObject) cursor.next();
                Date time_temp = (Date) temp.get("timestamp");
                long timestamp_temp = time_temp.getTime();
                if (timestamp_temp < treshold) {
                    String target = temp.getString("username");
                    gMIRC_handler.SoftDelete(target);
                }
            }
            HardClean();
        } finally {
            cursor.close();
        }

    } catch (UnknownHostException ex) {
        Logger.getLogger(gMIRC_server.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Highscores.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    try {//from   w  w w.j  ava2  s  .co  m
        String user;
        int count = 1;
        String highscore;
        jTextArea2.append("SR No.\tUSERNAME\tHIGHSCORE\n");
        int high;
        MongoClient mc = new MongoClient("localhost", 27017);
        DB db = mc.getDB("Classic_Hangman");
        System.out.println("Connected to database successfully!!");
        DBCollection coll = db.getCollection("high_score");
        System.out.println("Collection Retrieved");
        DBCursor cursor = coll.find();
        cursor.sort(new BasicDBObject("value", -1));
        while (cursor.hasNext() && count < 4) {
            DBObject result = cursor.next();
            high = ((Number) result.get("value")).intValue();
            highscore = Integer.toString(high);
            user = (String) result.get("_id");
            jTextArea2.append(count + "\t" + user + "\t" + highscore + "\n");
            count++;
        }
    } catch (UnknownHostException ex) {
        Logger.getLogger(Highscores.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Add_cust.java

@Override
/* Check The code below for insertion of values */
public void actionPerformed(ActionEvent ae) {
    // TODO Auto-generated method stub
    add(jLabel9);//w  w w . ja  va2s  . co  m
    String History = jComboBox3.getSelectedItem().toString();
    if (ae.getSource() == jButton1) {
        try {
            MongoClient mongo = new MongoClient("localhost", 27017);
            DB db = mongo.getDB("Gym");
            DBCollection Gym_Collection = db.getCollection("Customers");
            DBCollection Allot = db.getCollection("Batch"); //Declaration of collection for Batch
            DBCursor cursor = Allot.find();
            float Slots, Morning, Evening, Night;
            cursor.next();
            Slots = Float.parseFloat(cursor.curr().get("Slots").toString());
            Morning = Float.parseFloat(cursor.curr().get("Morning").toString());
            Evening = Float.parseFloat(cursor.curr().get("Evening").toString());
            Night = Float.parseFloat(cursor.curr().get("Night").toString());
            String first_name = jTextField1.getText();
            String last_name = jTextField2.getText();
            float weight = Float.parseFloat(jTextField6.getText().toString());
            float height = Float.parseFloat(jTextField5.getText().toString());
            String address = jTextArea1.getText();
            int age = Integer.parseInt(jComboBox1.getSelectedItem().toString());
            String Subs = jComboBox2.getSelectedItem().toString();

            String Batches = jComboBox5.getSelectedItem().toString();
            String phone_number = jTextField3.getText().toString();
            if (!isAlpha(first_name) || !isAlpha(last_name)) {
                JOptionPane.showMessageDialog(this, "Enter a valid name");
                jTextField1.setText("");
                jTextField2.setText("");
            } else if (weight > 150 || weight < 40) {
                JOptionPane.showMessageDialog(this, "Please add weight between 40 and 150");
                jTextField6.setText("");
            } else if (height > 250 || height < 50) {
                JOptionPane.showMessageDialog(this, "Please add height between 100 and 250");
                jTextField5.setText("");
            } else if (phone_number.length() < 8 || phone_number.length() > 11) {
                JOptionPane.showMessageDialog(this, "Enter a valid Phone no.");
                jTextField3.setText("");
            } else {
                int random_1, random_2, sub_sum = 0, days = 0;
                if (Subs.equals("1 Month")) {
                    sub_sum = 1000;
                    days = 30;
                } else if (Subs.equals("2 Months")) {
                    sub_sum = 1500;
                    days = 60;
                } else if (Subs.equals("3 Months")) {
                    sub_sum = 2250;
                    days = 90;
                } else if (Subs.equals("1 YEAR")) {
                    sub_sum = 6000;
                    days = 360;
                }
                int flag = 0, flag1 = 0, flag2 = 0, flag3 = 0;
                if (Batches.equals("Morning")) {
                    Morning += 1;
                    flag1 = 1;
                } else if (Batches.equals("Evening")) {
                    Evening += 1;
                    flag2 = 1;
                } else if (Batches.equals("Night")) {
                    Night += 1;
                    flag3 = 1;
                }
                if (Morning > Slots || Evening > Slots || Night > Slots) {
                    if (flag1 == 1) {
                        Morning -= 1;
                    } else if (flag2 == 1) {
                        Evening -= 1;
                    } else if (flag3 == 1) {
                        Night -= 1;
                    }
                    flag = 1;
                }
                if (flag == 1) {
                    float temp1, temp2;
                    if (flag1 == 1) {
                        temp1 = Slots - Evening;
                        temp2 = Slots - Night;
                        JOptionPane.showMessageDialog(this, "This time slot slot is full. Evening has " + temp1
                                + " Slots. Night has " + temp2 + " Slots.");
                    } else if (flag2 == 1) {
                        temp1 = Slots - Morning;
                        temp2 = Slots - Night;
                        JOptionPane.showMessageDialog(this, "This time slot slot is full. Morning has " + temp1
                                + " Slots. Night has " + temp2 + " Slots.");
                    } else {
                        temp1 = Slots - Morning;
                        temp2 = Slots - Evening;
                        JOptionPane.showMessageDialog(this, "This time slot slot is full. Morning has " + temp1
                                + " Slots. Evening has " + temp2 + " Slots.");
                    }
                } else {
                    do {
                        random_1 = (int) Math.floor(Math.random() * 360);
                        random_2 = (int) Math.floor(Math.random() * 360);
                    } while (random_1 >= random_2 || days <= random_2);
                    BasicDBObject doc = new BasicDBObject("First_Name", first_name.toLowerCase())
                            .append("Last_Name", last_name.toLowerCase()).append("Phone_Number", phone_number)
                            .append("Age", age).append("Height", height).append("History", History)
                            .append("Subscribe", days).append("Batch", Batches).append("Weight", weight)
                            .append("Attended", random_1).append("Total", random_2).append("Fees", sub_sum)
                            .append("Address", address);
                    Gym_Collection.insert(doc);
                    jTextField1.setText("");
                    jTextField2.setText("");
                    jTextField3.setText("");
                    jTextField5.setText("");
                    jTextField6.setText("");
                    jTextArea1.setText("");

                    BasicDBObject newDocument = new BasicDBObject();
                    newDocument.append("$set", new BasicDBObject().append("Morning", Morning)
                            .append("Evening", Evening).append("Night", Night));

                    BasicDBObject searchQuery = new BasicDBObject().append("Slots", Slots);

                    Allot.update(searchQuery, newDocument);

                    this.setVisible(false);
                    new work(History, first_name.toLowerCase(), last_name.toLowerCase());
                    this.setVisible(false);
                    new work().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("");
            jTextField2.setText("");
            jTextField3.setText("");
            jTextField5.setText("");
            jTextField6.setText("");
            jTextArea1.setText("");
        }
    }

    else if (ae.getSource() == jButton2) {
        this.setVisible(false);
        new Receptionist().setVisible(true);
    }
}

From source file:PersistMongo.java

public static void main(String[] args) {
    // conectando ao mongo, como esta sem parametros
    //se conecta ao mongo local por default 
    MongoClient mongoClient = new MongoClient("localhost", 27017);

    // Base de dados
    DB db = (DB) mongoClient.getDB("JavaDB");
    // Tabela /* w w  w  .  j  a  va  2 s  .  c o  m*/
    DBCollection collection = db.getCollection("colJava");
    // objeto para ser persistido
    BasicDBObject document1 = new BasicDBObject();
    document1.put("id", 1001);
    document1.put("msg", "Persistencia com mongoDB");

    // salvando o documento na base nosql
    collection.insert(document1);
    BasicDBObject document = new BasicDBObject();
    document = new BasicDBObject();
    document.put("id", 1002);
    document.put("msg", "Java + Mongo");

    // salvando o documento na base nosql
    collection.insert(document);
    // objeto que recebe os dados do banco
    DBCursor cursor = collection.find();
    // percorrendo o objeto e mostrando os dados
    while (cursor.hasNext()) {
        System.out.println("Document: " + cursor.next());

    }
    // Passando o documento que sera removido
    collection.remove(document);
    // Passando o documentoque sera atualizado e o documento que entrara em seu lugar 
    collection.update(document, document1);

}

From source file:Add_train.java

@Override
/* Check The code below for insertion of values */
public void actionPerformed(ActionEvent ae) {
    // TODO Auto-generated method stub
    add(jLabel9);// www. j a v a 2  s .  co m
    jLabel9.setText("");
    if (ae.getSource() == jButton1) {
        try {
            MongoClient mongo = new MongoClient("localhost", 27017);
            DB db = mongo.getDB("Gym");
            DBCollection Allot = db.getCollection("Batch_Trainer");
            DBCursor cursor1 = Allot.find();
            DBCollection Gym_Collection = db.getCollection("trainer");
            String first_name = jTextField1.getText();
            String last_name = jTextField2.getText();
            String password = jPassword1.getText().toString();
            String dup = jPassword2.getText().toString();
            String username = jTextField5.getText().toString();
            String address = jTextArea1.getText();

            String Batches = jComboBox5.getSelectedItem().toString();
            float Slots, Morning, Evening, Night;
            cursor1.next();
            Slots = Float.parseFloat(cursor1.curr().get("Slots").toString());
            Morning = Float.parseFloat(cursor1.curr().get("Morning").toString());
            Evening = Float.parseFloat(cursor1.curr().get("Evening").toString());
            Night = Float.parseFloat(cursor1.curr().get("Night").toString());
            int age = Integer.parseInt(jComboBox1.getSelectedItem().toString());
            String phone_number = jTextField3.getText().toString();
            DBCursor cursor = Gym_Collection.find();
            int i = 0;
            while (cursor.hasNext()) {
                cursor.next();
                if (username.equals(cursor.curr().get("Username").toString())) {
                    i = 1;
                }
            }
            if (i == 1) {
                JOptionPane.showMessageDialog(this, "Username has been taken !!!");
                jTextField5.setText("");
            } else if (!isAlpha(first_name) || !isAlpha(last_name)) {
                JOptionPane.showMessageDialog(this, "Enter a valid name");
                jTextField1.setText("");
                jTextField2.setText("");
            } else if (phone_number.length() < 8 || phone_number.length() > 10) {
                JOptionPane.showMessageDialog(this, "Enter a valid Phone no.");
                jTextField3.setText("");
            } else if (!password.equals(dup)) {
                JOptionPane.showMessageDialog(this, "Passwords didn't match");
                jPassword1.setText("");
                jPassword2.setText("");
            } else {

                int flag = 0, flag1 = 0, flag2 = 0, flag3 = 0;
                if (Batches.equals("Morning")) {
                    Morning += 1;
                    flag1 = 1;
                } else if (Batches.equals("Evening")) {
                    Evening += 1;
                    flag2 = 1;
                } else if (Batches.equals("Night")) {
                    Night += 1;
                    flag3 = 1;
                }
                if (Morning > Slots || Evening > Slots || Night > Slots) {
                    if (flag1 == 1) {
                        Morning -= 1;
                    } else if (flag2 == 1) {
                        Evening -= 1;
                    } else if (flag3 == 1) {
                        Night -= 1;
                    }
                    flag = 1;
                }
                if (flag == 1) {
                    float temp1, temp2;
                    if (flag1 == 1) {
                        temp1 = Slots - Evening;
                        temp2 = Slots - Night;
                        JOptionPane.showMessageDialog(this, "This time slot slot is full. Evening has " + temp1
                                + " Slots. Night has " + temp2 + " Slots.");
                    } else if (flag2 == 1) {
                        temp1 = Slots - Morning;
                        temp2 = Slots - Night;
                        JOptionPane.showMessageDialog(this, "This time slot slot is full. Morning has " + temp1
                                + " Slots. Night has " + temp2 + " Slots.");
                    } else {
                        temp1 = Slots - Morning;
                        temp2 = Slots - Evening;
                        JOptionPane.showMessageDialog(this, "This time slot slot is full. Morning has " + temp1
                                + " Slots. Evening has " + temp2 + " Slots.");
                    }
                } else {

                    BasicDBObject doc = new BasicDBObject("First_Name", first_name.toLowerCase())
                            .append("Last_Name", last_name.toLowerCase()).append("Batch", Batches)
                            .append("Phone_Number", phone_number).append("Age", age)
                            .append("Username", username).append("Password", password)
                            .append("Address", address);
                    Gym_Collection.insert(doc);
                    jTextField1.setText("");
                    jTextField2.setText("");
                    jTextField3.setText("");
                    jTextField5.setText("");
                    jPassword1.setText("");
                    jPassword2.setText("");
                    jTextArea1.setText("");
                    jLabel9.setFont(new java.awt.Font("SansSerif", 3, 16)); // NOI18N
                    jLabel9.setForeground(new java.awt.Color(204, 255, 204));
                    jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
                    jLabel9.setText("Successfully Added");
                    jLabel9.setBounds(200, 10, 200, 40);

                    BasicDBObject newDocument = new BasicDBObject();
                    newDocument.append("$set", new BasicDBObject().append("Morning", Morning)
                            .append("Evening", Evening).append("Night", Night));

                    BasicDBObject searchQuery = new BasicDBObject().append("Slots", Slots);

                    Allot.update(searchQuery, newDocument);

                    setVisible(true);
                }
            }
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "Please Check the Data types");
            jTextField1.setText("");
            jTextField2.setText("");
            jTextField3.setText("");
            jTextField5.setText("");
            jPassword1.setText("");
            jPassword2.setText("");
            jTextArea1.setText("");
        }
    }

    else if (ae.getSource() == jButton2) {
        this.setVisible(false);
        new Admin().setVisible(true);
    }
}

From source file:login_page.java

private void LoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoginActionPerformed
    // TODO add your handling code here:
    try {//from   w w  w.  j  a  va  2 s  .c om
        int check = 0;
        userid = UserID.getText();
        password = Password.getText();
        submit = Login.getActionCommand();

        if (radio_check == -99)
            JOptionPane.showMessageDialog(null, "Please Chhose Admin/Employee");
        else {
            if (radio_check == 0) {
                if ((userid.equals("admin")) && (password.equals("password123"))) {
                    System.out.println("Done");

                    //TO connect theses two pages..
                    setVisible(false);
                    new Admin_rights().setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(null, "Invalid Admin Login");
                }
            } else {
                MongoClient mc = new MongoClient("localhost", 27017);
                DB db = mc.getDB("parking_system");
                DBCollection collection = db.getCollection("employee_info");
                /*ISERT DOCUMENT 
                BasicDBObject doc = new BasicDBObject("userid",userid).append("password",password);
                collection.insert(doc);
                */
                DBCursor cursor = collection.find();
                DBObject obj;

                String temp_user, temp_pass;

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

                    temp_user = obj.get("_id").toString();
                    temp_pass = obj.get("password").toString();

                    if ((userid.equals(temp_user)) && (password.equals(temp_pass))) {
                        System.out.println("Done");

                        //TO connect theses two pages..
                        setVisible(false);
                        /*new Vehicle_type_check().setVisible(true);*/
                        new Entry_OR_Exit().setVisible(true);
                        check = 1;
                        break;
                    }
                }
                if (check != 1) {
                    JOptionPane.showMessageDialog(null, "Authentication Failed!\nInvalid Login");
                }
            }
        }
    } catch (Exception e) {

    }
}

From source file:act.server.MongoDB.java

License:Open Source License

public static P<P<List, List>, Map<Object, Object>> compare(String coll, String id_key, int thisport,
        int refport, boolean listsAreSet) throws UnknownHostException {
    String host = "localhost";
    String dbs = "actv01";

    List<Object> add = new ArrayList<Object>();
    List<Object> del = new ArrayList<Object>();
    Set<Object> seen = new HashSet<Object>();
    Map<Object, Object> upd = new HashMap<Object, Object>();

    DBCollection c = new Mongo(host, thisport).getDB(dbs).getCollection(coll);
    DBCollection cref = new Mongo(host, refport).getDB(dbs).getCollection(coll);

    // yes, we indeed need to iterate over the entire collection! so unrestricted find() ok here.
    DBCursor cur = c.find();
    while (cur.hasNext()) {
        DBObject doc = cur.next();//from  w ww .jav a  2 s.co  m
        Object id = doc.get(id_key);

        DBObject docref = findOneDoc(cref, id_key, id);
        if (docref == null) {
            // reference collection does not have doc, log as newly created
            add.add(id);
        } else {
            // reference collection has doc:
            // compare the differences between these two docs and log it as updated if they differ

            Object diff = compare(doc, docref, listsAreSet);
            if (diff != null) {
                // the docs differ. Log it as updated, and note the diff
                upd.put(id, diff);
            }
        }
        seen.add(id);
    }

    // now iterate over ref db and see if there are any docs deleted (i.e., not in notDeleted)
    DBCursor curref = c.find();
    while (curref.hasNext()) {
        DBObject doc = curref.next();
        Object id = doc.get(id_key);

        if (!seen.contains(id)) {
            // this doc was not seen in the updated collection, so deleted. log that
            del.add(id);
        }
    }

    return new P<P<List, List>, Map<Object, Object>>(new P<List, List>(add, del), upd);
}

From source file:AdminServer.ServiceS.java

private ArrayList getData(DBCollection collection, methodS type, String name) {
    ArrayList data = new ArrayList<>();
    DBCursor cursor;/*from  w  w  w  .j  a  v a  2 s . c  o  m*/

    if (type == methodS.ATM) {
        cursor = collection.find();
        while (cursor.hasNext()) {
            DBObject obj = cursor.next();
            String no = obj.get("SerialNum").toString();
            String ip = obj.get("ipAddr").toString();
            String money = obj.get("money").toString();
            String usr = obj.get("currentUser").toString();
            data.add(new tellerD(no, ip, money, usr));
        }
    } else if (type == methodS.USER) {
        cursor = collection.find(new BasicDBObject("name", name));
        while (cursor.hasNext()) {
            DBObject obj = cursor.next();
            String usr = obj.get("name").toString();
            boolean ip = (boolean) obj.get("locked");
            data.add(new userD(usr, ip));
        }
    } else if (type == methodS.TRADE) {
        cursor = collection.find(new BasicDBObject("ipAddr", name));
        while (cursor.hasNext()) {
            DBObject obj = cursor.next();
            String no = obj.get("serial").toString();
            String ip = obj.get("ipAddr").toString();
            String method = obj.get("type").toString();
            String usr = obj.get("name").toString();
            String delta = obj.get("delta").toString();
            String remains = obj.get("remains").toString();
            String date = obj.get("time").toString();
            data.add(new tradeD(no, ip, usr, method, delta, remains, date));
        }
    }
    return data;
}

From source file:aic2013.extractor.MongoDataAccess.java

public void forAll(Processor<Status> processor) {
    DB db = mongoClient.getDB("twitterdb");
    DBCollection statusCollection = db.getCollection("statuses");
    DBCursor cursor = statusCollection.find();

    while (cursor.hasNext()) {
        try {//from  ww  w. jav  a  2 s. co  m
            processor.process(DataObjectFactory.createStatus(cursor.next().toString()));
        } catch (TwitterException ex) {
            Logger.getLogger(MongoDataAccess.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}