Example usage for com.mongodb MongoClient getDB

List of usage examples for com.mongodb MongoClient getDB

Introduction

In this page you can find the example usage for com.mongodb MongoClient getDB.

Prototype

@Deprecated 
public DB getDB(final String dbName) 

Source Link

Document

Gets a database object.

Usage

From source file:govt_import_export.Order.java

private void sort_cars() {
    MongoClient mongo = null;
    try {/*w w  w  . jav a2 s .  co  m*/
        mongo = new MongoClient("localhost", 27017);
        //get database
    } catch (UnknownHostException | MongoException e) {
    }
    String[] st = new String[10];
    st[0] = "HYUNDAI";
    st[1] = "MARUTISUZUKI";
    st[2] = "NISSAN";
    st[3] = "BAJAJ";
    st[4] = "KTM";
    st[5] = "VOLKSVAGEN";
    DB db = mongo.getDB("AUTOMOBILEXPO");
    DBCollection table;

    ArrayList<Order> arr = new ArrayList<Order>();
    for (int j = 0; j < 6; j++) {
        table = db.getCollection(st[j]);

        if (table.findOne() != null) {
            String map = "function () {" + "emit(this.model,this.Units);" + "}";
            String reduce;
            reduce = "function (key,value) { " + "return Array.sum(value)}";

            MapReduceCommand cmd = new MapReduceCommand(table, map, reduce, null,
                    MapReduceCommand.OutputType.INLINE, null);

            MapReduceOutput out = table.mapReduce(cmd);
            String str;
            for (DBObject o : out.results()) {
                str = o.get("value").toString().trim();
                System.out.println(str);
                int i = 0;
                // var i=(int)(Convert.ToDouble("1.2"));
                //int a = int.Parse("1.2".Split('.')[0]);
                if (!str.equals(null)) {
                    Float f = Float.parseFloat(str);
                    i = (int) Math.ceil(f);
                    arr.add(new Order(o.get("_id").toString(), i) {

                        @Override
                        public int compare(Order o1, Order o2) {
                            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                        }

                        @Override
                        public int compareTo(Order o) {
                            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                        }
                    });
                }
            }
        }

    }
    Collections.sort(arr, new Order() {
    });
    for (Order a : arr)
        System.out.println(" " + a.getid() + " " + a.getval());
    this.dispose();
    Sorted s = new Sorted(arr);
    s.setVisible(true);

}

From source file:govt_import_export.display_2.java

private void disp(String s) {
    MongoClient mongo = null;
    int x = 0;//from  ww w .  j av a  2 s . c  o  m
    try {
        mongo = new MongoClient("localhost", 27017);
    } catch (UnknownHostException | MongoException e) {
    }
    if (jTable1.getRowCount() > 0) {
        for (int i = jTable1.getRowCount() - 1; i > -1; i--) {
            model.removeRow(i);
        }
    }
    DB db = mongo.getDB("AUTOMOBILEXPO");
    String[] st = new String[10];
    st[0] = "HYUNDAI";
    st[1] = "MARUTISUZUKI";
    st[2] = "NISSAN";
    st[3] = "BAJAJ";
    st[4] = "KTM";
    st[5] = "VOLKSVAGEN";
    String s1, s2, s3;
    s1 = jComboBox1.getSelectedItem().toString();
    s2 = jComboBox2.getSelectedItem().toString();
    s3 = jComboBox3.getSelectedItem().toString();
    BasicDBObject search = new BasicDBObject();
    BasicDBObject result = new BasicDBObject();
    BasicDBObject sp = new BasicDBObject();
    if (s.equals(s1)) {
        int i = Integer.parseInt(s);
        sp.put("Year", i);
        if (jCheckBox2.isSelected() && jCheckBox3.isSelected()) {

            sp.append("country", s2);
            sp.append("manufacturer", s3);
        } else if (jCheckBox2.isSelected()) {
            sp.append("country", s2);
        } else if (jCheckBox3.isSelected()) {
            sp.append("manufacturer", s3);
        }

    } else if (s.equals(s2)) {
        sp.put("country", s2);
        int i = Integer.parseInt(s1);
        if (jCheckBox1.isSelected() && jCheckBox3.isSelected()) {
            sp.append("Year", i);
            //sp.append("country",s2);
            sp.append("manufacturer", s3);
        } else if (jCheckBox1.isSelected()) {
            //sp.append("country",s2);
            sp.append("Year", i);
        } else if (jCheckBox3.isSelected()) {
            sp.append("manufacturer", s3);
        }

    } else if (s.equals(s3)) {
        sp.put("manufacturer", s3);
        int i = Integer.parseInt(s1);
        if (jCheckBox1.isSelected() && jCheckBox2.isSelected()) {
            sp.append("Year", i);
            sp.append("country", s2);
            //sp.append("manufacturer",s3);
        } else if (jCheckBox1.isSelected()) {
            //sp.append("country",s2);
            sp.append("Year", i);
        } else if (jCheckBox2.isSelected()) {
            sp.append("country", s2);
        }

    }
    ArrayList<String> arr = new ArrayList();
    for (int j = 0; j <= 5; j++) {
        DBCollection table;

        table = db.getCollection(st[j]);
        if (table.findOne() != null) {
            DBCursor cr = table.find(sp);
            DBObject obj;

            while (cr.hasNext()) {
                obj = cr.next();
                x++;
                //jLabel1.setText(jLabel1.getText()+"Model\n"+(obj.toString())+"\n");
                //jTextArea1.
                //  jTextArea1.setText(jTextArea1.getText()+"Manufacture:   "+(obj.get("manufacturer").toString())+"    Model: "+(obj.get("model").toString())+"   Units : "+(obj.get("Units").toString())+"Cost : "+(obj.get("Cost").toString())+" Continent  : "+(obj.get("country").toString())+"  Year :"+(obj.get("Year").toString())+"\n");        
                model.addRow(new Object[] { obj.get("manufacturer").toString(), (obj.get("model").toString()),
                        (obj.get("Units").toString()), (obj.get("Cost").toString()),
                        (obj.get("country").toString()), (obj.get("Year").toString()) });
            }

        }
    }

    total = x;
    String a = Integer.toString(total);
    jLabel5.setText(a);

}

From source file:govt_import_export.display_2.java

private void simple_display() {
    MongoClient mongo = null;
    try {//from  www .ja  v a2s.  co m
        mongo = new MongoClient("localhost", 27017);

    } catch (UnknownHostException | MongoException e) {
    }
    // String batches=(String)jComboBox1.getSelectedItem( );
    //get collections
    if (jTable1.getRowCount() > 0) {
        for (int i = jTable1.getRowCount() - 1; i > -1; i--) {
            model.removeRow(i);
        }
    }

    int x = 0;
    DB db = mongo.getDB("AUTOMOBILEXPO");
    String[] st = new String[10];
    st[0] = "HYUNDAI";
    st[1] = "MARUTISUZUKI";
    st[2] = "NISSAN";
    st[3] = "BAJAJ";
    st[4] = "KTM";
    st[5] = "VOLKSVAGEN";
    ArrayList<String> arr = new ArrayList();
    for (int j = 0; j <= 5; j++) {
        DBCollection table;

        table = db.getCollection(st[j]);
        if (table.findOne() != null) {
            BasicDBObject search = new BasicDBObject();
            BasicDBObject result = new BasicDBObject();
            BasicDBObject sp = new BasicDBObject();
            DBCursor cr = table.find();
            //System.out.println(table.findOne());
            String str;
            DBObject obj;
            while (cr.hasNext()) {
                x++;
                obj = cr.next();
                //jTextArea1.setText(jTextArea1.getText()+"  Manufacture : "+(obj.get("manufacturer").toString())+"       Model : "+(obj.get("model").toString())+"       Units : "+(obj.get("Units").toString())+"     Cost : "+(obj.get("Cost").toString())+"    Continent  : "+(obj.get("country").toString())+"      Year : "+(obj.get("Year").toString())+"\n");    
                model.addRow(new Object[] { obj.get("manufacturer").toString(), (obj.get("model").toString()),
                        (obj.get("Units").toString()), (obj.get("Cost").toString()),
                        (obj.get("country").toString()), (obj.get("Year").toString()) });

            }

        }
    }

    total = x;
    String a = Integer.toString(total);
    jLabel5.setText(a);

}

From source file:govt_import_export.export.java

public export(String item1, String item2) {
    initComponents();//w w w. j a  va 2s  .c  o  m
    model_selected = item1;
    manufac = item2;
    MongoClient mongo = null;
    try {
        mongo = new MongoClient("localhost", 27017);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

    catch (MongoException e) {
        e.printStackTrace();
    }
    DB db = mongo.getDB("automobile_expo");
    DBCollection table = db.getCollection(manufac);
    BasicDBObject doc = new BasicDBObject();
    BasicDBObject doc1 = new BasicDBObject();

    String s = new String();
    doc.put("model_name", model_selected);
    doc1.append("_id", 0);
    DBCursor c = table.find(doc, doc1);
    //while(c.hasNext())
    {
        DBObject doc2 = c.next();
        //System.out.println(doc2.toString());
        jLabel6.setText("<html>Model " + (doc2.get("model_name").toString()) + "<br> date "
                + (doc2.get("date").toString()) + " <br>EngineType" + (doc2.get("EngineType").toString())
                + "<br>EngineDisplacement" + (doc2.get("EngineDisplacement").toString()) + "<br>Maximum_torque"
                + (doc2.get("Maximum_torque").toString()) + "<br>Noof_cylinders"
                + (doc2.get("Noof_cylinders").toString()) + "<br>Seating_Capacity"
                + (doc2.get("Seating_Capacity").toString()) + "<br>Length" + (doc2.get("Length").toString())
                + "<br>Width" + (doc2.get("Width").toString()) + "<br>Height" + (doc2.get("Height").toString())
                + "<br>Cost" + (doc2.get("Cost").toString()) + "</html>");
        //jTextArea1.setText(s);

    }
    String[] split = s.split(",");

    //jTextArea1.setText(s);
    doc.put("model_name", model_selected);
    BasicDBObject sp = new BasicDBObject();
    sp.put("Cost", 1);
    sp.put("_id", 0);
    DBCursor cursor = table.find(doc, sp);
    while (cursor.hasNext())
        z = cursor.next().toString();
    z = z.substring(z.indexOf("st\" : \"") + 7);
    z = z.substring(0, z.indexOf("INR"));
    String s2;
    //while(cursor.hasNext())

    //BasicDBObject h=(BasicDBObject)cursor.next();
    //s2=h.get("Cost").toString();

    //insert
    cost = Integer.parseInt(z);
    total_cost = 1000 * cost;
    String st;
    st = String.valueOf(total_cost);
    jTextField1.setText(st);
    //jTextField1.setText(z);

}

From source file:govt_import_export.export.java

private void sort_cars() {
    try {/*from   w w  w .  ja v a2 s . c  o m*/
        MongoClient mongo = new MongoClient("localhost", 27017);
        //get database
        DB db = mongo.getDB("AUTOMOBILEXPO");
        String batches = (String) jComboBox1.getSelectedItem();
        //get collections
        DBCollection table = db.getCollection(manufac);
        BasicDBObject search = new BasicDBObject();
        BasicDBObject sp = new BasicDBObject();
        //sp.put("Units",1);
        sp.put("_id", 0);
        search.put("model", model_selected);
        DBCursor cursor = table.find(search, sp).sort(new BasicDBObject("Units", 1));

        while (cursor.hasNext()) {
            r = cursor.next().toString();
            System.out.println(r);
        }
        /*String map="function(){"+"String model;"+"model=col;"+"emit(model,{Units:this.Units});}";
        String reduce="function(key,values){"+"int sum=0;"+"values.forEach(function(doc){" + "sum += this.Units; " + "}); " +"return {table: sum};} ";
        MapReduceCommand cm = new MapReduceCommand(table, map,reduce, null, MapReduceCommand.OutputType.INLINE, null);
             MapReduceOutput out = table.mapReduce(cm);
             System.out.println("Mapreduce results");
             for (DBObject o : out.results()) {
                   System.out.println(o.toString());
             }*/
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

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

}

From source file:govt_import_export.export.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    // TODO add your handling code here:
    MongoClient mongo = null;
    try {/*from w w  w. j  a  v a2s  .  c om*/
        mongo = new MongoClient("localhost", 27017);
        //get database
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

    catch (MongoException e) {
        e.printStackTrace();
    }
    DB db = mongo.getDB("AUTOMOBILEXPO");
    //DB db2=mongo.getDB("automobile_expo");
    String batches = (String) jComboBox1.getSelectedItem();
    int unit, month, year;

    unit = Integer.parseInt(batches);
    //get collections
    DBCollection table = db.getCollection(manufac);
    //DBCollection table1=db2.getCollection(db1);
    BasicDBObject document1 = new BasicDBObject();
    String st = (String) jComboBox2.getSelectedItem();
    String st1 = (String) jComboBox3.getSelectedItem();
    String st2 = (String) jComboBox4.getSelectedItem();
    month = Integer.parseInt(st1);
    year = Integer.parseInt(st2);

    cost = cost * unit;
    //jTextField1.setText(z);
    DB db0 = mongo.getDB("admindata");
    DBCollection collection0 = db0.getCollection("admin");
    DBCursor c = collection0.find(); //yes            
    DBObject o;
    //DBCursor c=collection0.find(); //yes  
    while (c.hasNext()) {
        o = c.next();
        if (o.get("rate") != null) {
            db_rate = o.get("rate").toString();
        }
    }

    c = collection0.find();

    while (c.hasNext()) {
        o = c.next();
        if (o.get("balance") != null) {
            db_balance = nf.format(o.get("balance"));

        }
    }

    ratio = ((double) cost) / Double.parseDouble(db_balance);
    ratio = -ratio * .1;
    newbalance = Long.parseLong(db_balance) - cost;
    newrate = Double.parseDouble(db_rate) * pow(Math.E, ratio);
    System.out.println("'newrate'" + newrate);
    //System.out.println(newbalance);
    String q = nf.format(newbalance);
    //System.out.println(q);

    //--------------------setting the updated values in the db----------------------

    BasicDBObject searchupdate = new BasicDBObject();
    searchupdate.append("rate", Double.parseDouble(db_rate)); //finds the document(s) where "date":last_activity

    BasicDBObject update = new BasicDBObject();
    update.append("$set", new BasicDBObject("rate", /*Double.toString(newrate)*/newrate));

    collection0.update(searchupdate, update);

    //-----
    BasicDBObject searchupdate1 = new BasicDBObject();
    searchupdate1.append("balance", Long.parseLong(db_balance));

    BasicDBObject update1 = new BasicDBObject();
    update1.append("$set", new BasicDBObject("balance", Long.parseLong(q)));

    collection0.update(searchupdate1, update1);

    //DBObject o;
    BasicDBObject document = new BasicDBObject();
    BasicDBObject prev = new BasicDBObject();
    document.append("manufacturer", manufac);
    document.append("model", model_selected);
    document.append("country", st);
    document.append("Units", unit);
    document.append("Cost", cost);

    document.append("Month", month);
    document.append("Year", year);
    table.insert(document);
    //long x=table.count();
    //find and display
    //System.out.println(x);
    GroupCommand cmd = new GroupCommand(table, null, new BasicDBObject("model", model_selected),
            new BasicDBObject("Units", 0), "function(document,prev){prev.Units=prev.Units+this.Units;}", null);
    o = table.group(cmd);
    //System.out.println(o);
    sort_cars();
    javax.swing.JOptionPane.showMessageDialog(export.this, "Waiting for acceptance");
    st = String.valueOf(total_cost);
    jTextField1.setText(st);
    System.out.println("donee");
}

From source file:govt_import_export.export.java

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    // TODO add your handling code here:
    JLabel p = new JLabel();
    MongoClient mongo = null;
    try {/*from  w  ww .  j a  va  2s  . c  o m*/
        mongo = new MongoClient("localhost", 27017);
        //get database
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

    catch (MongoException e) {
        e.printStackTrace();
    }
    DB db = mongo.getDB("AUTOMOBILEXPO");
    DBCollection table = db.getCollection(manufac);
    String map = "function () {" + "emit(this.model,this.Units);" + "}";
    String reduce = "function (key, values) { " + "return Array.sum(values)}";

    MapReduceCommand cmd = new MapReduceCommand(table, map, reduce, null, MapReduceCommand.OutputType.INLINE,
            null);

    MapReduceOutput out = table.mapReduce(cmd);

    for (DBObject o : out.results()) {
        System.out.println(o.toString());
    }

}

From source file:gr.teicm.toulou.SignupResource.java

@POST
@Consumes("text/plain")
public String postUser(String user) {
    System.out.println(user);/*  w w  w  .ja  va 2s .c om*/
    Gson gson = new Gson();
    DBObject dbObjectUser = (DBObject) JSON.parse(user);
    System.out.println("parsed leei");

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    System.out.println("connected leei");

    DB db = mongoClient.getDB("snapchatydb");
    System.out.println("fetched db leei");
    DBCollection coll = (DBCollection) db.getCollection("user");
    System.out.println("fetched collection leei");

    coll.insert(dbObjectUser);
    System.out.println("inserted leei");
    return "";
}

From source file:guesslocation.MongoQuery.java

public static void main(String[] args) {

    {/*from   w  w  w. j av  a  2s .  com*/

        try {

            // Connect to mongodb
            MongoClient mongo = new MongoClient("localhost", 27017);

            // get database
            // if database doesn't exists, mongodb will create it for you
            DB db = mongo.getDB("test");

            // get collection
            // if collection doesn't exists, mongodb will create it for you
            DBCollection collection = db.getCollection("twitter");
            DBCollection Outcollection = db.getCollection("user_tw");
            DBCursor cursor;
            BasicDBObject query;
            //------------------------------------
            // ( 1 ) collection.find() --> get all document
            cursor = collection.find();
            System.out.println("( 1 ) .find()");
            System.out.println("results --> " + cursor.count());

            try {
                BasicDBObject IDquery = new BasicDBObject(); //2015-05-12T15:15:31Z
                while (cursor.hasNext()) {
                    DBObject data = cursor.next();
                    Long v_user_Id = (Long) data.get("user_Id");
                    if (v_user_Id == null) {
                        continue;
                    }

                    IDquery.append("user_Id", v_user_Id);
                    DBCursor IDcursor = Outcollection.find(IDquery);
                    if (IDcursor.hasNext() == false) {
                        BasicDBObject basicObj = GetUserRecord(v_user_Id, data);
                        try {
                            Outcollection.insert(basicObj);
                        } catch (Exception e) {
                            System.err.println("error on insert " + v_user_Id);
                        }
                        basicObj = null;
                        Thread.sleep(100);
                        Outcollection.ensureIndex(new BasicDBObject("user_Id", 1),
                                new BasicDBObject("unique", true));
                    }
                    IDcursor.close();
                    IDquery.clear();
                }
            } catch (InterruptedException ex) {
                Logger.getLogger(MongoQuery.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                cursor.close();
            }

            System.out.println("---------------------------------");
            System.exit(0);

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

    }

}

From source file:it.wami.map.mongodeploy.OsmToMongoDB.java

License:Apache License

/**
 * @param args//from   ww  w .ja v  a2 s.c om
 */
public static void main(String[] args) {

    if (args == null || args.length == 0 || args.length < 2) {
        System.out.println(Options.USAGE);
        return;
    }

    parseCommandOptions(args);

    MongoClientOptions mco = new MongoClientOptions.Builder().connectionsPerHost(150000)
            .threadsAllowedToBlockForConnectionMultiplier(10000).build();

    MongoClient mongoClient = createMongo(options.getHost(), options.getPort(), mco);

    DB db = mongoClient.getDB(options.getDbName());
    DBCollection nodes = db.createCollection(OsmSaxHandler.COLL_NODES, null);
    createNodesIndex(nodes);
    /*DBCollection ways = */
    DBCollection ways = db.createCollection(OsmSaxHandler.COLL_WAYS, null);
    createWaysIndex(ways);
    /*DBCollection relations = */
    DBCollection relations = db.createCollection(OsmSaxHandler.COLL_RELATIONS, null);
    createRelationsIndex(relations);
    db.createCollection(OsmSaxHandler.COLL_TAGS, null);

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = null;
    try {
        saxParser = factory.newSAXParser();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    DefaultHandler handler = new OsmSaxHandler(db, options);

    try {
        if (options.getInput().contains(".bz2")) {
            try {
                saxParser.parse(getInputStreamForBZ2File(options.getInput()), handler);
            } catch (CompressorException e) {
                e.printStackTrace();
            }
        } else if (options.getInput().contains(".osm")) {
            saxParser.parse(options.getInput(), handler);
        } else {
            throw new IllegalArgumentException("input must be an osm file or a bz2.");
        }
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}