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:com.stratio.tests.ATExampleMongoDB.java

License:Apache License

@BeforeClass
public void setUp() throws UnknownHostException {
    MongoClient mongoClient = new MongoClient(mongoHost, mongoPort);
    mongoClient.dropDatabase(dataBase);/*from   w w w. j a v a2s .  c om*/
    DB db = mongoClient.getDB(dataBase);
    DBCollection tabletest = db.getCollection("tabletest");
    // DBCollection tabletest = db.createCollection("tabletest");
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    format.setTimeZone(TimeZone.getTimeZone("CET"));
    for (int i = 0; i < 10; i++) {
        Date parsedDate = null;
        String fecha = i + "/" + i + "/200" + i;
        try {
            parsedDate = format.parse(fecha);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(new java.sql.Date(parsedDate.getTime()).toString());
        BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start().add("ident", i)
                .add("name", "name_" + i).add("money", 10.2 + i).add("new", true)
                .add("date", new java.sql.Date(parsedDate.getTime()));
        tabletest.insert(documentBuilder.get());
    }
    //   DBObject aux = tabletest.findOne();
    //  java.sql.Date aux1 = (java.sql.Date)aux.get("date");
    mongoClient.close();
    String connector = "Mongo";
    //Preparamos las cositas para compartir
    ThreadProperty.set("Host", "127.0.0.1");
    ThreadProperty.set("Connector", connector);

}

From source file:com.syncleus.maven.plugins.mongodb.StartMongoMojo.java

License:Open Source Community License

DB connectToMongoAndGetDatabase(final String databaseName) throws MojoExecutionException {
    if (databaseName == null || databaseName.trim().length() == 0) {
        throw new MojoExecutionException("Database name is missing");
    }//from  www .j  ava  2s.c o m

    final MongoClient mongoClient = new MongoClient("localhost", getPort());
    getLog().info("Connected to MongoDB");
    return mongoClient.getDB(databaseName);
}

From source file:com.tengen.Final7.java

License:Apache License

public static void main(String[] args) throws IOException {
    MongoClient client = new MongoClient();
    DB db = client.getDB("photoshare");
    int i = 0;/*  w w w  .j  a  v a 2  s.  c  om*/
    DBCollection album = db.getCollection("albums");
    DBCollection image = db.getCollection("images");

    DBCursor cur = image.find();
    cur.next();

    while (cur.hasNext()) {
        Object id = cur.curr().get("_id");
        DBCursor curalbum = album.find(new BasicDBObject("images", id));
        if (!curalbum.hasNext()) {
            image.remove(new BasicDBObject("_id", id));
        }
        cur.next();
    }
}

From source file:com.tengen.Final8.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient();
    DB db = client.getDB("test");
    DBCollection animals = db.getCollection("animals");

    BasicDBObject animal = new BasicDBObject("animal", "monkey");

    animals.insert(animal);/*from  ww  w. java  2s .  c  om*/
    animal.removeField("animal");
    animal.append("animal", "cat");
    animals.insert(animal);
    animal.removeField("animal");
    animal.append("animal", "lion");
    animals.insert(animal);
}

From source file:com.tengen.FindUsers.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient();
    DB db = client.getDB("blog");
    DBCollection collection = db.getCollection("users");
    //collection.drop();

    // insert 10 documents with a random integer as the value of field "x"

    System.out.println("\nFind all: ");
    DBCursor cursor = collection.find(new BasicDBObject("_id", "andrzej1"));

    try {//from  w  w w  .  j a  v  a 2s  .  c o m
        while (cursor.hasNext()) {
            DBObject cur = cursor.next();
            System.out.println(cur.get("_id"));
        }
    } finally {
        cursor.close();
    }

    System.out.println("\nCount:");
    long count = collection.count();
    System.out.println(count);
}

From source file:com.tengen.helloworld.HelloWorldMongoDBSparkFreemarkerStyle.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(HelloWorldSparkFreemarkerStyle.class, "/");

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

    DB database = client.getDB("course");
    final DBCollection collection = database.getCollection("hello");

    Spark.get(new Route("/") {
        @Override// w  w  w .ja va2 s . c  o  m
        public Object handle(final Request request, final Response response) {
            StringWriter writer = new StringWriter();
            try {
                Template helloTemplate = configuration.getTemplate("hello.ftl");

                DBObject document = collection.findOne();

                helloTemplate.process(document, writer);
            } catch (Exception e) {
                halt(500);
                e.printStackTrace();
            }
            return writer;
        }
    });
}

From source file:com.tengen.helloworld.HelloWorldMongoDBStyle.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));

    DB database = client.getDB("course");
    DBCollection collection = database.getCollection("hello");

    DBObject document = collection.findOne();
    System.out.println(document);
}

From source file:com.tengen.home.Week1Homework3.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient();

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

    // Not necessary yet to understand this.  It's just to prove that you
    // are able to run a command on a mongod server
    AggregationOutput output = collection.aggregate(
            new BasicDBObject("$group",
                    new BasicDBObject("_id", "$value").append("count", new BasicDBObject("$sum", 1))),
            new BasicDBObject("$match", new BasicDBObject("count", new BasicDBObject("$gt", 2))),
            new BasicDBObject("$sort", new BasicDBObject("_id", 1)));

    int answer = 0;
    for (DBObject doc : output.results()) {
        answer += (Double) doc.get("_id");
    }//from  ww w .  j  a  va2 s. co  m

    System.out.println("THE ANSWER IS: " + answer);
}

From source file:com.tengen.home.Week1Homework4.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(Week1Homework4.class, "/");

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

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

    Spark.get(new Route("/") {
        @Override// ww  w. j av  a2s  . c  o  m
        public Object handle(final Request request, final Response response) {
            StringWriter writer = new StringWriter();
            try {
                Template helloTemplate = configuration.getTemplate("answer.ftl");

                // Not necessary yet to understand this.  It's just to prove that you
                // are able to run a command on a mongod server
                AggregationOutput output = collection.aggregate(
                        new BasicDBObject("$group",
                                new BasicDBObject("_id", "$value").append("count",
                                        new BasicDBObject("$sum", 1))),
                        new BasicDBObject("$match", new BasicDBObject("count", new BasicDBObject("$lte", 2))),
                        new BasicDBObject("$sort", new BasicDBObject("_id", 1)));

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

                Map<String, String> answerMap = new HashMap<String, String>();
                answerMap.put("answer", Integer.toString(answer));

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

From source file:com.tengen.Week3Homework1Stream.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient();

    DB database = client.getDB("school");
    DBCollection collection = database.getCollection("students");

    try (DBCursor students = collection.find()) {
        students.forEach(student -> {
            BasicDBList scores = (BasicDBList) student.get("scores");
            DBObject worstHomeScoreDoc = scores.stream().map(o -> (DBObject) o) // cast Object to DBObject
                    .filter(o -> o.get("type").equals("homework"))
                    .min((o1, o2) -> ((Double) o1.get("score")).compareTo((Double) o2.get("score"))).get();
            scores.remove(worstHomeScoreDoc);

            collection.update(new BasicDBObject("_id", student.get("_id")), student);
        });//from   w  ww  .ja v  a2  s  . com
    }
}