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:module.UpdateNumberSamples.java

License:Open Source License

public UpdateNumberSamples() {

    // ===== Connection =====

    MongoClient mongoClient = MongoUtil.buildMongoClient();
    MongoDatabase db = mongoClient.getDatabase("epimed_experiments");

    MongoCollection<Document> collectionSeries = db.getCollection("series");
    MongoCollection<Document> collectionSamples = db.getCollection("sample");

    // String [] listIdSeries = {"TISSUE_SPECIFIC_GENES_MM"};
    // List<Document> listSeries = collectionSeries.find(Filters.in("_id", listIdSeries)).into(new ArrayList<Document>());

    List<Document> listSeries = collectionSeries.find().into(new ArrayList<Document>());

    for (Document ser : listSeries) {
        System.out.println(ser);/*  w w  w  . j  ava  2s  .  co  m*/

        String idSeries = ser.getString("_id");
        Bson filter = Filters.in("series", idSeries);

        Long nbSamples = collectionSamples.count(filter);

        System.out.println(idSeries + " " + nbSamples);

        ser.append("nb_samples", nbSamples);
        collectionSeries.updateOne(Filters.eq("_id", idSeries), new Document("$set", ser));

    }

    mongoClient.close();

}

From source file:module.UpdatePlatformType.java

License:Open Source License

public UpdatePlatformType() {

    // ===== Connection =====

    MongoClient mongoClient = MongoUtil.buildMongoClient();
    MongoDatabase db = mongoClient.getDatabase("epimed_experiments");
    MongoCollection<Document> collectionPlatforms = db.getCollection("platform");
    MongoCollection<Document> collectionSeries = db.getCollection("series");

    // ===== Platforms =====

    Bson filters = Filters.eq("type", "unknown");
    List<Document> listPlatforms = collectionPlatforms.find(filters).into(new ArrayList<Document>());

    for (Document platform : listPlatforms) {
        System.out.println("--------------------------------------------------------------");

        String idPlatform = platform.getString("_id");
        System.out.println(platform);
        List<Document> listSeries = collectionSeries.find(Filters.in("platforms", idPlatform))
                .into(new ArrayList<Document>());
        for (Document series : listSeries) {
            System.out.println(" \t -> " + series.getString("_id") + " " + series.getString("title"));
        }//from  www.j  a va  2s  .c  o m

        // platform.append("type", "expression array");
        // collectionPlatforms.updateOne(Filters.eq("_id", idPlatform), new Document("$set", platform));

    }

    mongoClient.close();
}

From source file:module.UpdateTissueStatus.java

License:Open Source License

public UpdateTissueStatus() {

    // ===== Connection =====

    MongoClient mongoClient = MongoUtil.buildMongoClient();
    MongoDatabase db = mongoClient.getDatabase("epimed_experiments");
    MongoCollection<Document> collectionSample = db.getCollection("sample");

    List<Document> samples = collectionSample.find().into(new ArrayList<Document>());
    ;/*from w  ww .jav a  2s .com*/

    for (Document sample : samples) {

        Document expgroup = sample.get("exp_group", Document.class);
        Integer idTissueStatus = expgroup.getInteger("id_tissue_status");
        if (idTissueStatus != null) {
            if (idTissueStatus.equals(1)) {
                expgroup.put("tissue_status", "normal");
            }
            if (idTissueStatus.equals(2)) {
                expgroup.put("tissue_status", "pathological_non_tumoral");
            }
            if (idTissueStatus.equals(3)) {
                expgroup.put("tissue_status", "tumoral");
            }

            sample.put("exp_group", expgroup);

            System.out.println(sample.get("exp_group", Document.class));

            collectionSample.updateOne(Filters.eq("_id", sample.getString("_id")),
                    new Document("$set", sample));

        }

    }

    mongoClient.close();

}

From source file:mongodb.QuickTour.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 *///from   w  ww .j a  va2  s .  c o m
public static void main(final String[] args) {

    //represents a pool of connections to the database
    MongoClient mongoClient = new MongoClient("10.9.17.105", 27017);

    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("test");

    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");

    // drop all the data in it
    collection.drop();

    // make a document and insert it
    Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1).append("info",
            new Document("x", 203).append("y", 102));

    collection.insertOne(doc);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    Document myDoc = collection.find().first();
    System.out.println(myDoc.toJson());

    // now, lets add lots of little documents to the collection so we can explore queries and cursors
    List<Document> documents = new ArrayList<Document>();
    for (int i = 0; i < 100; i++) {
        documents.add(new Document("i", i));
    }
    collection.insertMany(documents);
    System.out.println(
            "total # of documents after inserting 100 small ones (should be 101) " + collection.count());

    // find first
    myDoc = collection.find().first();
    System.out.println(myDoc.toJson());

    // lets get all the documents in the collection and print them out
    MongoCursor<Document> cursor = collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }

    for (Document cur : collection.find()) {
        System.out.println(cur.toJson());
    }

    // now use a query to get 1 document out
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc.toJson());

    // now use a range query to get a larger subset
    cursor = collection.find(gt("i", 50)).iterator();

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }

    // range query with multiple constraints
    cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator();

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }

    // Query Filters
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc.toJson());

    // now use a range query to get a larger subset
    Block<Document> printBlock = new Block<Document>() {
        @Override
        public void apply(final Document document) {
            System.out.println(document.toJson());
        }
    };
    collection.find(gt("i", 50)).forEach(printBlock);

    // filter where; 50 < i <= 100
    collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock);

    // Sorting
    myDoc = collection.find(exists("i")).sort(descending("i")).first();
    System.out.println(myDoc.toJson());

    // Projection
    myDoc = collection.find().projection(excludeId()).first();
    System.out.println(myDoc.toJson());

    // Update One
    collection.updateOne(eq("i", 10), new Document("$set", new Document("i", 110)));

    // Update Many
    UpdateResult updateResult = collection.updateMany(lt("i", 100),
            new Document("$inc", new Document("i", 100)));
    System.out.println(updateResult.getModifiedCount());

    // Delete One
    collection.deleteOne(eq("i", 110));

    // Delete Many
    DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
    System.out.println(deleteResult.getDeletedCount());

    collection.drop();

    // ordered bulk writes
    List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
    writes.add(new InsertOneModel<Document>(new Document("_id", 4)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 5)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 6)));
    writes.add(
            new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2))));
    writes.add(new DeleteOneModel<Document>(new Document("_id", 2)));
    writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4)));

    collection.bulkWrite(writes);

    collection.drop();

    collection.bulkWrite(writes, new BulkWriteOptions().ordered(false));
    collection.find().forEach(printBlock);

    // Clean up
    //        database.drop();

    // release resources
    mongoClient.close();
}

From source file:mongodb.QuickTourAdmin.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args//from   w  w w .j a  v  a  2s  .c om
 *            takes an optional single argument for the connection string
 */
public static void main(final String[] args) {
    MongoClient mongoClient;

    if (args.length == 0) {
        // connect to the specified database server
        mongoClient = new MongoClient("10.9.17.105", 27017);
    } else {
        mongoClient = new MongoClient(new MongoClientURI(args[0]));
    }

    // get handle to "test" database
    MongoDatabase database = mongoClient.getDatabase("test");

    database.drop();

    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");

    // drop all the data in it
    collection.drop();

    // getting a list of databases
    for (String name : mongoClient.listDatabaseNames()) {
        System.out.println(name);
    }

    // drop a database
    mongoClient.getDatabase("databaseToBeDropped").drop();

    // create a collection
    database.createCollection("cappedCollection",
            new CreateCollectionOptions().capped(true).sizeInBytes(0x100000));

    for (String name : database.listCollectionNames()) {
        System.out.println(name);
    }

    // drop a collection:
    collection.drop();

    // create an ascending index on the "i" field
    // 1 ascending or -1 for descending
    collection.createIndex(new Document("i", 1));

    // list the indexes on the collection
    for (final Document index : collection.listIndexes()) {
        System.out.println(index.toJson());
    }

    // create a text index on the "content" field
    // text indexes to support text search of string content
    collection.createIndex(new Document("content", "text"));

    collection.insertOne(new Document("_id", 0).append("content", "textual content"));
    collection.insertOne(new Document("_id", 1).append("content", "additional content"));
    collection.insertOne(new Document("_id", 2).append("content", "irrelevant content"));

    // Find using the text index
    long matchCount = collection.count(text("textual content -irrelevant"));
    System.out.println("Text search matches: " + matchCount);

    // Find using the $language operator
    Bson textSearch = text("textual content -irrelevant", "english");
    matchCount = collection.count(textSearch);
    System.out.println("Text search matches (english): " + matchCount);

    // Find the highest scoring match
    Document projection = new Document("score", new Document("$meta", "textScore"));
    Document myDoc = collection.find(textSearch).projection(projection).first();
    System.out.println("Highest scoring document: " + myDoc.toJson());

    // Run a command
    Document buildInfo = database.runCommand(new Document("buildInfo", 1));
    System.out.println(buildInfo);

    // release resources
    database.drop();
    mongoClient.close();
}

From source file:mongodbmanipulation.MongoDBManipulation.java

/**
 * @param args the command line arguments
 *//*from   w  w w  . j  a  v  a2 s  .  c  o  m*/
public static void main(String[] args) {
    // TODO code application logic here
    UserInterface.main(args);
    try {
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase db = mongoClient.getDatabase("test");
        System.out.println("Connect to database successfully");
        //        boolean auth = db.authenticate(myUserName, myPassword);
        //        System.out.println("Authentication: "+auth);

        MongoCollection<Document> coll = db.getCollection("animals");

        FindIterable<Document> cursor = coll.find();
        int i = 0;
        for (Iterator iterator = cursor.iterator(); iterator.hasNext(); i++) {
            System.out.println(iterator.next());
            if (i == 100)
                break;
        }

    } catch (Exception e) {
        System.out.println("Failed!");
    }
}

From source file:mongodb_teste.Jmongo.java

private void jBInserirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBInserirActionPerformed
    // TODO add your handling code here:
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase("BDprject");
    db.getCollection("Professores")
            .insertOne(new Document("nome", jInNomeProf.getText()).append("email", jInemailProf.getText())
                    .append("materias", asList(new Document().append("nome", jInMateriaProf.getText())
                            .append("nota", jInNotaProf.getText())))
                    .append("telefone", jIntelefoneProf.getText()));
    JOptionPane.showMessageDialog(null, "Inserido com sucesso");
    mongoClient.close();/*from   w  ww  . ja  v a2 s.c om*/
}

From source file:mongodb_teste.Jmongo.java

private void jBProfSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBProfSearchActionPerformed
    // TODO add your handling code here:
    jshowProfSearch.setText("");
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase("BDprject");
    Iterable<Document> iterable = db.getCollection("Professores")
            .aggregate(Arrays.asList((Aggregates.match(new Document("nome", jSearchName.getText()))),
                    Aggregates.unwind("$materias"),
                    Aggregates.group("$materias.nota", Accumulators.sum("total", 1)),
                    Aggregates.sort(new Document("total", -1))));
    Iterator<Document> it = iterable.iterator();
    while (it.hasNext()) {
        jshowProfSearch.append(it.next().toString() + "\n");
    }//from   w ww  .j av  a  2  s .c  o  m
    mongoClient.close();
}

From source file:mongodb_teste.Jmongo.java

private void jBMatSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBMatSearchActionPerformed
    // TODO add your handling code here:
    jshowMateriaSearch.setText("");
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase("BDprject");
    Iterable<Document> iterable = db.getCollection("Professores")
            .find(new Document("materias.nome", jMatSearch.getText()));
    Iterator<Document> it = iterable.iterator();
    while (it.hasNext()) {
        jshowMateriaSearch.append(it.next().toString() + "\n");
    }//from   www .  j  a v  a2  s . c  o  m
    mongoClient.close();
}

From source file:mongodb_teste.Jmongo.java

private void jBinsertMatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBinsertMatActionPerformed
    // TODO add your handling code here:
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase("BDprject");
    db.getCollection("Professores").updateOne(new Document("nome", jMatInNomeProf.getText()),
            new Document("$push", new Document("materias",
                    new Document("nome", jMatInNome.getText()).append("nota", jMatInNota.getText()))));
    JOptionPane.showMessageDialog(null, "Inserido com sucesso");
    mongoClient.close();//from  w  ww. j a v a 2 s . c om
}