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:mongodb.tedc.Week1Homework4.java

License:Apache License

public static void main(String[] args) throws IOException {
    /* ------------------------------------------------------------------------ */
    /* You should do this ONLY ONCE in the whole application life-cycle:        */

    /* Create and adjust the configuration singleton */
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_21);
    cfg.setDirectoryForTemplateLoading(new File("src/main/resources"));
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);

    MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));

    DB database = client.getDB("m101");
    final DBCollection collection = database.getCollection("funnynumbers");

    get("/", (req, res) -> {

        StringWriter writer = new StringWriter();
        try {//from w  ww .  ja va2s  . co m
            // Not necessary yet to understand this.  It's just to prove that you
            // are able to run a command on a mongod server
            DBObject groupFields = new BasicDBObject("_id", "$value");
            groupFields.put("count", new BasicDBObject("$sum", 1));
            DBObject group = new BasicDBObject("$group", groupFields);

            DBObject match = new BasicDBObject("$match",
                    new BasicDBObject("count", new BasicDBObject("$lte", 2)));

            DBObject sort = new BasicDBObject("$sort", new BasicDBObject("_id", 1));

            // run aggregation
            List<DBObject> pipeline = Arrays.asList(group, match, sort);

            AggregationOutput output = collection.aggregate(pipeline);

            int answer = 0;
            for (DBObject doc : output.results()) {
                answer += (Double) doc.get("_id");
            }

            /* Create a data-model */
            Map<String, String> answerMap = new HashMap<>();
            answerMap.put("answer", Integer.toString(answer));

            /* Get the template (uses cache internally) */
            Template helloTemplate = cfg.getTemplate("answer.ftl");

            /* Merge data-model with template */
            helloTemplate.process(answerMap, writer);

        } catch (Exception e) {
            logger.error("Failed", e);
            halt(500);
        }
        return writer;
    });
}

From source file:mongodb1.Mongodb1.java

/**
 * @param args the command line arguments
 *//*  w  w w  .  ja v  a2  s  .c om*/
public static void main(String[] args) {

    try { //Connect

        MongoClient mongo = new MongoClient();
        DB db = mongo.getDB("labbd2016");
        System.out.println("Connect to database successfully");

        DBCollection table = db.getCollection("alunos");
        System.out.println("Collection retrieved successfully");

        List<String> dbs = mongo.getDatabaseNames();
        System.out.println(dbs);

        Set<String> collections = db.getCollectionNames();
        System.out.println(collections);
        //Insert
        BasicDBObject document = new BasicDBObject();
        document.put("nome", "Adao");
        document.put("idade", 30);
        table.insert(WriteConcern.SAFE, document);
        for (DBObject doc : table.find()) {
            System.out.println(doc);
        }
        //Find
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("idade", new BasicDBObject("$gt", 1));
        DBCursor cursor = table.find(searchQuery);
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

From source file:mx.org.cedn.avisosconagua.mongo.UpdateIssueDate.java

License:Open Source License

public static void main(String[] arg) throws Exception {
    MongoClientURI mongoClientURI = new MongoClientURI(System.getenv("MONGOHQ_URL"));
    MongoClient mongoClient = new MongoClient(mongoClientURI);
    DB mongoDB = mongoClient.getDB(mongoClientURI.getDatabase());
    String GENERATED_COL = "GeneratedFiles";
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
    SimpleDateFormat isoformater = new SimpleDateFormat("YYYY-MM-dd HH:mm");
    if (null != mongoClientURI.getUsername()) {
        mongoDB.authenticate(mongoClientURI.getUsername(), mongoClientURI.getPassword());
    }/* ww w  .j  a  va 2s  .c o  m*/
    DBCollection col = mongoDB.getCollection(GENERATED_COL);
    DBCursor cursor = col.find();
    for (DBObject obj : cursor) {
        String date = (String) obj.get("issueDate");
        Date fec = null;
        try {
            fec = sdf.parse(date);
        } catch (ParseException npe) {

        }
        if (null != fec) {
            date = isoformater.format(fec);
            DBObject act = col.findOne(obj);
            obj.put("issueDate", date);
            col.update(act, obj);
        }
    }
}

From source file:myapp.MongoDBConnection.java

License:Apache License

public void test() {
    MongoClient mongoClient = null;
    try {/*from  w w w . j  a  v  a  2s  . c  o m*/
        mongoClient = new MongoClient("localhost", 27017);
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //String server = "mongodb://webuser:toniotonio@ds055709.mongolab.com:55709";
    //String conectionString = "mongodb://webuser:toniotonio@ds055709.mongolab.com:55709";
    //   MongoClientURI mongoConecctionURI = new MongoClientURI(conectionString);
    //   MongoClient mongoClient = new MongoClient(mongoConecctionURI);

    DB db = mongoClient.getDB("primal-manifest");
    //boolean auth = db.authenticate("webuser", "toniotonio".toCharArray());

    //MongoClient mongoClient = new MongoClient();
    // get handle to "mydb"
    mongoClient.close();

}

From source file:myControls.Main_view.java

private myPanel getGrid() {
    myPanel pnl = new myPanel();
    myTable table = new myTable();
    pnl.add(table);//  www .  j  a v a 2 s. c  o  m
    //
    MongoClient mongoClient = null;
    DBCursor cursor = null;
    mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB("kiaan");
    DBCollection coll = db.getCollection("banks");
    cursor = coll.find();
    String[] columnNames = { "id", "name" };
    DefaultTableModel model = new DefaultTableModel(columnNames, 0);
    while (cursor.hasNext()) {
        DBObject obj = cursor.next();
        String first = (String) obj.get("name");
        ObjectId id = (ObjectId) obj.get("_id");
        model.addRow(new Object[] { id, first });
    }
    table.setModel(model);
    cursor.close();
    mongoClient.close();
    //
    return pnl;
}

From source file:mypackage.CollInformation.java

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. */
        try {/*w  ww .j  a  v a2s .  c  om*/
            String getDBName = request.getParameter("dbname");
            String getCollName = request.getParameter("collname");
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            DB mongoDatabase = mongoClient.getDB(getDBName);
            DBCollection coll = mongoDatabase.getCollection(getCollName);
            long totalDoc = coll.count();
            JSONObject jSONObject = new JSONObject();
            JSONArray jSONArray = new JSONArray();

            DBCursor cursor = coll.find();
            int i = 0;
            while (cursor.hasNext()) {
                jSONArray.put(cursor.next());
                i++;
            }
            jSONObject.put("db", jSONArray);
            jSONObject.put("counter", i);
            jSONObject.put("totalDoc", totalDoc);
            out.println(jSONObject);

        } catch (Exception e) {

        }
    }
}

From source file:mypackage.CreateColl.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        try {//from   w w w.ja  v  a 2  s .co  m
            String getDBName = request.getParameter("dbname");
            String getCollName = request.getParameter("collname");
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            DB mongoDatabase = mongoClient.getDB(getDBName);
            DBObject bObject = new BasicDBObject();
            bObject.put(getDBName, getCollName);
            if (!collectionExists(getDBName, mongoDatabase)) {
                mongoDatabase.createCollection(getCollName, bObject);
                //BasicDBObject doc = new BasicDBObject();
                // doc.put("name",getCollName);
                //  dBCollection.insert(doc);
                out.print("true");
            } else {
                out.print("false");
            }

        } catch (Exception e) {

        }
    }
}

From source file:mypackage.CreateDB.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        String getDBName = request.getParameter("dbname");
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        HttpSession httpSession = request.getSession(false);
        DB db = mongoClient.getDB("mydb");
        DBCollection dBCollection = db.getCollection(httpSession.getAttribute("uname") + "DB");
        BasicDBObject dBObject = new BasicDBObject();
        dBObject.put("kapil", getDBName);
        WriteResult writeResult = dBCollection.insert(dBObject);

        if (writeResult.getN() == 0) {
            out.print("true");
            MongoDatabase mongoDatabase = mongoClient.getDatabase(getDBName);
            mongoDatabase.createCollection("Welcome");
            mongoDatabase.drop();//w w w . ja v a2s. c om
        } else {
            out.print("false");
        }

    }
}

From source file:mypackage.DownloadColl.java

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. */
        try {//from   w w  w  . j a v a2  s . c o  m
            String dbname = request.getParameter("dbname");
            String collname = request.getParameter("collname");
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            DB db = mongoClient.getDB(dbname);
            // out.print(dbname+collname);

            JSONObject jSONObject_coll = new JSONObject();
            JSONArray jSONObject_doc = new JSONArray();
            DBCollection dBCollection = db.getCollection(collname);

            DBCursor dBCursor = dBCollection.find();
            while (dBCursor.hasNext()) {
                DBObject next1 = dBCursor.next();
                jSONObject_doc.put(next1);

            }
            //out.print(dbname+collname);
            String filename = dbname + "_" + collname + ".json";

            jSONObject_coll.put(collname, jSONObject_doc);
            //out.print(jSONObject_coll);
            File file = checkExist("mongocollection.json");
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write(jSONObject_coll.toString());
            fileWriter.close();
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
            FileInputStream fis = new FileInputStream(dir + "\\" + "mongocollection.json");
            int i;
            while ((i = fis.read()) != -1) {
                out.write(i);

            }
            fis.close();
            out.close();
        } catch (Exception e) {

        }
    }
}

From source file:mypackage.DownloadDB.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        try {//w  ww.  j  a  va 2  s  .  c o m
            // To connect to mongodb server
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            // Now connect to your databases

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

            DB db = mongoClient.getDB(dbname);
            Set<String> collNames = db.getCollectionNames();
            Iterator<String> iterator = collNames.iterator();
            JSONObject jSONObject_db = new JSONObject();
            JSONObject jSONObject_coll = new JSONObject();
            JSONArray jSONObject_doc = new JSONArray();

            while (iterator.hasNext()) {
                String next = iterator.next();
                DBCollection dBCollection = db.getCollection(next);
                DBCursor dBCursor = dBCollection.find();
                while (dBCursor.hasNext()) {
                    DBObject next1 = dBCursor.next();
                    jSONObject_doc.put(next1);

                }
                jSONObject_coll.put(next, jSONObject_doc);

            }
            String filename = dbname + ".json";
            jSONObject_db.put(dbname, jSONObject_coll);
            File file = checkExist("mongodb.json");
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write(jSONObject_db.toString());
            fileWriter.close();
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
            FileInputStream fis = new FileInputStream(dir + "\\" + "mongodb.json");
            int i;
            while ((i = fis.read()) != -1) {
                out.write(i);

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

    }
}