Example usage for com.mongodb MongoClient getDatabase

List of usage examples for com.mongodb MongoClient getDatabase

Introduction

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

Prototype

public MongoDatabase getDatabase(final String databaseName) 

Source Link

Usage

From source file:com.mycompany.database.MongodbDataBaseClass.java

public void dududu() {
    System.out.println("not error");
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase database = mongoClient.getDatabase("testdb");
    System.out.println("not error");
    MongoCollection<Document> col = database.getCollection("cars");

    try (MongoCursor<Document> cur = col.find().iterator()) {
        while (cur.hasNext()) {

            Document doc = cur.next();

            List list = new ArrayList(doc.values());
            System.out.print(list.get(1));
            System.out.print(": ");
            System.out.println(list.get(2));
        }/*w ww. j  a v a  2 s  . co  m*/
    }

    mongoClient.close();
}

From source file:com.mycompany.mavenproject2.VirtualkeyController.java

private static void createTable(/*Section subCatPart*/String tableName, Paragraph preface)
        throws BadElementException {
    try {/*from  www  .jav  a 2s.c  o  m*/
        ArrayList<String> list = new ArrayList<String>();

        // t.setBorderColor(BaseColor.GRAY);
        // t.setPadding(4);
        // t.setSpacing(4);
        // t.setBorderWidth(1);
        int length = 0;
        java.sql.Connection conn = Connection.getConnect();
        Statement st = conn.createStatement();
        st = conn.createStatement();
        ResultSet rs = st.executeQuery("SELECT * FROM " + tableName);

        ResultSetMetaData rsMetaData = rs.getMetaData();

        int numberOfColumns = rsMetaData.getColumnCount();
        System.out.println("resultSet MetaData column Count=" + numberOfColumns);
        for (int i = 1; i <= numberOfColumns; i++) {
            length = i;
        }
        MongoClient client = new MongoClient();
        MongoDatabase db = client.getDatabase("FinalDemo");

        PdfPTable table = new PdfPTable(length);

        for (int i = 1; i <= numberOfColumns; i++) {
            // System.out.println("column MetaData ");
            //System.out.println("column number " + i);
            // get the column's name.
            System.out.println(rsMetaData.getColumnName(i));
            PdfPCell c1 = new PdfPCell(new Phrase(rsMetaData.getColumnName(i)));
            c1.setHorizontalAlignment(Element.ALIGN_CENTER);
            list.add(rsMetaData.getColumnName(i));
            table.addCell(c1);
        }
        while (rs.next()) {
            for (String col : list) {
                //System.out.println("Column name is "+col+"value is "+rs.getString(col));
                table.addCell(rs.getString(col));
            }
        }
        /*PdfPCell c1 = new PdfPCell(new Phrase("Table Header 1"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);
                
        c1 = new PdfPCell(new Phrase("Table Header 2"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);
                
        c1 = new PdfPCell(new Phrase("Table Header 3"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);*/
        table.setHeaderRows(1);

        preface.add(table);
        //subCatPart.add(table);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(VirtualkeyController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(VirtualkeyController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.mycompany.mongodb_exercise.MongoDBQueries.java

public MongoDBQueries(String clientURI, String dbName, String collectionName) {
    this.clientURI = clientURI;
    this.dbName = dbName;
    this.collectionName = collectionName;
    MongoClientURI connStr = new MongoClientURI(clientURI);
    MongoClient mongoClient = new MongoClient(connStr);
    db = mongoClient.getDatabase(dbName);
    collection = db.getCollection(collectionName);
}

From source file:com.mycompany.team2.TeamTest2.java

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

    MongoClientURI uri = new MongoClientURI(
            "mongodb://kay:myRealPassword@mycluster0-shard-00-00-wpeiv.mongodb.net:27017,mycluster0-shard-00-01-wpeiv.mongodb.net:27017,mycluster0-shard-00-02-wpeiv.mongodb.net:27017/admin?ssl=true&replicaSet=Mycluster0-shard-0&authSource=admin");

    MongoClient mongoClient = new MongoClient(uri);
    DB database;//from  w w w.java2s .co m
    database = (DB) mongoClient.getDatabase("test");
    System.out.println("Hello sir again");
    System.out.println("Hello boss how art thou");
    System.out.println("Good afternoone");
    System.out.println("Good afternoon");
    System.out.println("Good day");

    System.out.println(addNum());
    System.out.println("GHk");
    System.out.println("GoodDay Sir");
    System.out.println("How art Though");
    System.out.println("Yes sir thank you");
    System.out.println("Email please");
    System.out.println("bbububub");
    System.out.println("Emailtest4");
    System.out.println("Emailtestfddf");
    System.out.println("Yoouj");
    System.out.println("Hello email");
    System.out.println("Thank god that worked");
    System.out.println("Thank god that workedgain a");

}

From source file:com.mysweethome.TemperaturePersisterTimerTask.java

public synchronized void persistDataOnMongolab() {
    //disable console logging
    //Logger mongoLogger = Logger.getLogger("org.mongodb.driver"); 
    //mongoLogger.setLevel(Level.SEVERE);

    iStoredTemperatures = iTemperatureStore.getTemperatures();
    if (iStoredTemperatures.isEmpty()) {
        logger.info("Nothing to persist. Exiting");
        return;/*from w  ww .  j av  a  2  s  .c o  m*/
    }
    logger.info("Prepairing to persist [{}] Temps in the cloud", iStoredTemperatures.size());
    MongoCollection<Document> mongoCollection = null;
    MongoClient client = null;
    List<Document> documents = new ArrayList<Document>();

    for (TemperatureMeasure tTemp : iStoredTemperatures) { //Exception in thread "Timer-2" java.util.ConcurrentModificationException
        Document doc = new Document();
        doc.put("Location", tTemp.getLocation()); //Location
        doc.put("Group", tTemp.getGroup()); //Group
        doc.put("Date", Helper.getDateAsString(tTemp.getDate())); //Date
        doc.put("Day", Helper.getDayAsString(tTemp.getDate()));
        doc.put("Time", Helper.getTimeAsString(tTemp.getDate()));
        doc.put("Temp", Helper.getTempAsString(tTemp.getTemp())); //Temp
        documents.add(doc);
        iPersistedTemperatures.add(tTemp);
    }

    try {
        MongoClientURI uri = new MongoClientURI(MySweetHomeProperties.ML_URL);
        client = new MongoClient(uri);
        MongoDatabase database = (MongoDatabase) client.getDatabase(uri.getDatabase());
        mongoCollection = database.getCollection("dailytemps");
        mongoCollection.insertMany(documents);
        //eliminate stored Temps from the collection
        iTemperatureStore.removeAll(iPersistedTemperatures);
        client.close();
        logger.info("Temperatures persisted on mongolab: [{}]. Exiting.", iPersistedTemperatures.size());
        iPersistedTemperatures.clear();
    } catch (Throwable e) {
        logger.error("Failed to store Temps in the cloud. Stacktrace: [{}]. Exiting.", e);
        iPersistedTemperatures.clear();
        e.printStackTrace();
    } finally {
        if (client != null) {
            client.close();
        }
        iPersistedTemperatures.clear();
    }
}

From source file:com.picdrop.guice.RepositoryModule.java

@Provides
@Singleton
@Override
protected MongoDatabase provideDatabase(MongoClient client) {
    return client.getDatabase("picdrop");
}

From source file:com.rorrell.personrest.data.MongoDbConnector.java

private MongoDbConnector() {
    MongoClient client = new MongoClient("localhost", 27017);
    db = client.getDatabase("testrest");
}

From source file:com.sborny.wordcountexample.MongoBolt.java

@Override
public void execute(Tuple input, BasicOutputCollector collector) {
    if (!dbIsSet) {
        MongoClient mongoClient = new MongoClient(m_ip, Integer.parseInt(m_port));
        db = mongoClient.getDatabase(dbName);
        System.out.println("GOT_DATABASE");
        dbIsSet = true;/*from   w w  w .jav a 2 s .  c  o m*/
    }

    System.out.println("DID_EXECUTE");
    JSONObject obj = new JSONObject(input.getStringByField(message));
    try {
        System.out.println("START_TRY");
        String collection = obj.getString("collectionId");
        JSONObject json = obj.getJSONObject(message);
        db.getCollection(collection).insertOne(Document.parse(json.toString()));
        System.out.println("END_TRY");
    } catch (JSONException ex) {
        System.out.println("START_EXC");
        String collection = "00000";
        db.getCollection(collection).insertOne(Document.parse(obj.toString()));
        System.out.println("END_EX");
    }
}

From source file:com.shiyq.mongodb.BulkInsertThread.java

@Override
public void run() {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase mongoDatabase = mongoClient.getDatabase("study");

    MongoCollection<Document> collection = mongoDatabase.getCollection("s_user");
    List<Document> list = new ArrayList<>();
    Document document;//w  w  w.j a v  a  2 s.  c o  m

    int i = 0;
    while (true) {
        if (i++ < 1000) {
            document = new Document();
            document.append("id", UUID.randomUUID());
            document.append("code", code);
            document.append("name", name);
            document.append("password", password);
            document.append("create_date", new Date());
            list.add(document);
        } else {
            //System.out.println(list.size());
            collection.insertMany(list);
            list.clear();
            i = 0;
        }
    }
}

From source file:com.shiyq.mongodb.InsertThread.java

@Override
public void run() {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase mongoDatabase = mongoClient.getDatabase("study");

    MongoCollection<Document> collection = mongoDatabase.getCollection("s_user");
    Document document;//ww  w .ja v a  2  s  .c o  m
    while (true) {
        document = new Document();
        document.append("code", code);
        document.append("name", name);
        document.append("password", password);
        document.append("create_date", new Date());

        collection.insertOne(document);
    }
}