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:io.mandrel.metadata.impl.MongoMetadataStore.java

License:Apache License

public MongoMetadataStore(TaskContext context, MongoClient mongoClient, String databaseName,
        String collectionName, int batchSize) {
    super(context);
    this.mongoClient = mongoClient;
    this.batchSize = batchSize;
    collection = mongoClient.getDatabase(databaseName).getCollection(collectionName);
}

From source file:io.sip3.tapir.salto.configuration.MongoConfiguration.java

License:Apache License

@Bean
public MongoDatabase db(MongoClientURI uri) {
    MongoClient client = new MongoClient(uri);
    return client.getDatabase(uri.getDatabase());
}

From source file:it.av.fac.dbi.util.FieldUpdater.java

public static void main(String[] args) {
    SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss Z yyyy");

    MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);
    MongoDatabase mongoDB = mongoClient.getDatabase("test");
    MongoCollection<Document> collection = mongoDB.getCollection("tweets");

    FindIterable<Document> documents = collection.find();
    documents.forEach(new Consumer<Document>() {
        @Override//from w w  w  .  j  a v  a 2s .  c o  m
        public void accept(Document doc) {
            try {
                //System.out.println(doc.toJson());
                Document user = (Document) doc.get("user");
                String dateStr = user.getString("created_at");
                //System.out.println(dateStr);
                Date date = parser.parse(dateStr);
                //System.out.println(date);
                System.out.println(collection.updateOne(eq("_id", doc.get("_id")),
                        new Document("$set", new Document("user.created_at", date))));
            } catch (ParseException ex) {
                Logger.getLogger(FieldUpdater.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
}

From source file:it.terrinoni.Controller.java

public static void main(String[] args) {
    MongoClient client = new MongoClient();
    MongoDatabase database = client.getDatabase("photo-sharing");

    MongoCollection<Document> albums = database.getCollection("albums");
    MongoCollection<Document> images = database.getCollection("images");

    albums.createIndex(new Document("images", 1));

    // Get the iterator of the whole collection
    MongoCursor<Document> cursor = images.find().iterator();

    try {/*from w  w w.j a va  2 s  .  c  om*/
        while (cursor.hasNext()) {
            Document currImg = cursor.next();
            Document foundImg = albums.find(eq("images", currImg.getDouble("_id"))).first();
            if (foundImg == null) {
                //System.out.println(currImg.getDouble("_id") + " deleted.");
                images.deleteOne(currImg);
            }
            //System.out.println(currImg.getDouble("_id") + " is ok.");
        }
    } finally {
        cursor.close();
    }

    long numImgs = images.count(eq("tags", "sunrises"));
    System.out.println("The total number of images with the tag \"sunrises\" after the removal of orphans is: "
            + String.valueOf(numImgs));
}

From source file:it.terrinoni.hw2.Homework.java

public static void main(String[] args) {
    MongoClient client = new MongoClient();
    MongoDatabase database = client.getDatabase("students");
    MongoCollection<Document> collection = database.getCollection("grades");

    Bson filter = eq("type", "homework");
    Bson sort = ascending(asList("student_id", "score"));

    MongoCursor<Document> cursor = collection.find(filter).sort(sort).iterator();

    double last_student_id = -1;

    try {//from  ww  w . j a v  a2 s . c  o m
        while (cursor.hasNext()) {
            Document doc = cursor.next();
            if (doc.getDouble("student_id") != last_student_id) {
                last_student_id = doc.getDouble("student_id");
                collection.deleteOne(doc);
                System.out.println("Document for " + last_student_id + " with score "
                        + String.valueOf(doc.getDouble("score")) + "  eliminated");
            }
            Helpers.printJson(doc);
        }
    } finally {
        cursor.close();
    }

}

From source file:it.terrinoni.hw3.PruneHomeworks.java

public static void main(String[] args) {
    // MongoDB connection
    MongoClient client = new MongoClient();
    MongoDatabase database = client.getDatabase("school");
    MongoCollection<Document> collection = database.getCollection("students");

    // Get the cursor to the collection
    MongoCursor<Document> cursor = collection.find().iterator();

    try {/* w  w w  . ja  va 2 s .  c o  m*/
        while (cursor.hasNext()) { // iteare over all the students
            double minScore = Double.MAX_VALUE; // set the maximum value
            Document minDoc = null; // temporary minimum
            Document student = cursor.next(); // current score

            // Retrieve the scores array
            List<Document> scores = student.get("scores", ArrayList.class);
            for (Document score : scores) { // iterate over the scores
                if (score.get("type", String.class).equals("homework")) { // get only the homeworks
                    System.out.println("Student " + student.getDouble("_id") + " has homework score equals to "
                            + score.getDouble("score"));
                    // Update the minimum score 
                    if (score.getDouble("score") < minScore) {
                        minScore = score.getDouble("score");
                        minDoc = score;
                    }
                }
            }
            // Remove the minimum score
            scores.remove(minDoc);

            // Update the student document
            Bson filter = eq("_id", student.getDouble("_id"));
            Document update = new Document("$set", new Document("scores", scores));
            collection.updateOne(filter, update);
        }
    } finally {
        cursor.close(); // close the cursos
    }
}

From source file:it.terrinoni.m101j.App.java

public static void main(String[] args) {
    MongoClientOptions options = MongoClientOptions.builder().connectionsPerHost(100).build();
    MongoClient client = new MongoClient(new ServerAddress(), options);

    MongoDatabase db = client.getDatabase("test").withReadPreference(ReadPreference.secondary());

    MongoCollection<BsonDocument> coll = db.getCollection("test", BsonDocument.class);
}

From source file:it.terrinoni.m101j.spark.HelloWorldMongoDBSparkFreemarkerStyle.java

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

    MongoClient client = new MongoClient();

    MongoDatabase database = client.getDatabase("course");
    final MongoCollection<Document> collection = database.getCollection("hello");

    collection.drop();//from   w w w.  j a v  a2s  . co m

    collection.insertOne(new Document("name", "MongoDB"));

    Spark.get("/", new Route() {
        @Override
        public Object handle(Request request, Response response) {
            StringWriter writer = new StringWriter();
            try {
                Template helloTemplate = configuration.getTemplate("hello.ftl");

                Document document = collection.find().first();

                helloTemplate.process(document, writer);

            } catch (IOException | TemplateException ex) {
                Spark.halt(500);
                ex.printStackTrace();
            }
            return writer;
        }
    });
}

From source file:it.terrinoni.Question.java

public static void main(String[] args) {
    MongoClient c = new MongoClient();
    MongoDatabase db = c.getDatabase("test");
    MongoCollection<Document> animals = db.getCollection("animals");

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

    animals.insertOne(animal);/*from   ww  w  . j ava  2s .c o  m*/

    animal.remove("animal");
    animal.append("animal", "cat");
    try {
        animals.insertOne(animal);
    } catch (MongoWriteException ex) {
        System.err.println(animal.getString("animal") + " not inserted");
    }

    animal.remove("animal");
    animal.append("animal", "lion");
    try {
        animals.insertOne(animal);
    } catch (MongoWriteException ex) {
        System.err.println(animal.getString("animal") + " not inserted");
    }

    long tot = animals.count();

    System.out.println("Total number of inserted animals: " + tot);
}

From source file:khp.pba.dba42.mongo.java

public static MongoDatabase db() {

    // To connect to mongodb server
    MongoClientURI conn = new MongoClientURI("mongodb://localhost:27017");
    MongoClient mongoClient = new MongoClient(conn);
    // Now connect to your databases
    MongoDatabase db = mongoClient.getDatabase("social_net");

    return db;/*from  ww w . j  av  a2s.  co m*/
}