Example usage for com.mongodb.client MongoDatabase getCollection

List of usage examples for com.mongodb.client MongoDatabase getCollection

Introduction

In this page you can find the example usage for com.mongodb.client MongoDatabase getCollection.

Prototype

MongoCollection<Document> getCollection(String collectionName);

Source Link

Document

Gets a collection.

Usage

From source file:io.mandrel.timeline.impl.MongoTimelineRepository.java

License:Apache License

@PostConstruct
public void init() {
    MongoDatabase database = mongoClient.getDatabase(properties.getMongoClientDatabase());

    MongoUtils.checkCapped(database, collectionName, size, maxDocuments);
    timeline = database.getCollection(collectionName);
}

From source file:it.av.fac.datasources.wikipedia.WikipediaSource.java

public WikipediaSource(String XMLFilePath) throws ParserConfigurationException, SAXException {
    this.parser = SAXParserFactory.newInstance().newSAXParser();
    this.fac = new APIClient("http://localhost:8080/FAC_Webserver");
    this.XMLFilePath = XMLFilePath;

    try (MongoClient mongoClient = new MongoClient("127.0.0.1", 27017)) {
        MongoDatabase mongoDB = mongoClient.getDatabase("fac");
        MongoCollection metadataCol = mongoDB.getCollection("metadata");
        this.SKIP = metadataCol.count();
    }//w  w  w . j  a v a  2 s . com
}

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. ja  v  a2  s . c om*/
        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 ww w .  j a  v a 2s . 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 {/*w w w  .j a v  a 2  s  . com*/
        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 {/*from   w  ww  . ja  v  a2  s . co  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.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();/* ww  w .  j a  v  a  2  s  .c o 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   w w w.  j a  v a 2 s  . co  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:kiaanfx.Kiaanfx.java

private static void agg() {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase db = mongoClient.getDatabase("kiaan");
    AggregateIterable<Document> iterable = db.getCollection("banks")
            .aggregate(asList(new Document("$unwind", "$branches")));

    iterable.forEach(new Block<Document>() {
        @Override//w w w. j  av  a 2  s. com
        public void apply(final Document document) {
            System.out.println(document.toJson());
        }
    });
}

From source file:modelo.modelo.java

public modelo() {
    MongoClient cliente = new MongoClient("localhost", 27017);
    MongoDatabase db = cliente.getDatabase("venta");
    clientes = db.getCollection("clientes");
    articulos = db.getCollection("articulos");
    ventas = db.getCollection("ventas");
}