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

License:Open Source License

public SearchPlatforms() {

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

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

    List<Document> list = collectionSamples
            .aggregate(Arrays.asList(Aggregates.group("$exp_group.id_platform", Accumulators.sum("total", 1)),
                    Aggregates.sort(Sorts.orderBy(Sorts.descending("total")))))
            .into(new ArrayList<Document>());

    for (int i = 0; i < list.size(); i++) {
        System.out.println((i + 1) + " " + list.get(i));
    }//from   w  w w.ja  v  a2 s.  com

    // collectionPlatforms.find(Filters.regex("title", ".*ethyl.*")).forEach(printBlock);
    collectionPlatforms.find(Filters.eq("id_organism", "9606")).forEach(printBlock);

    mongoClient.close();

}

From source file:module.test.SearchSamples.java

License:Open Source License

public SearchSamples() {

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

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

    List<Document> list = collectionSamples.find(Filters.and(Filters.eq("exp_group.id_tissue_stage", 4),
            Filters.ne("exp_group.main_gse_number", "GSE30654"))).into(new ArrayList<Document>());

    for (Document document : list) {
        System.out.println(document);
    }//  w w w .  j  av  a2 s.c o m

    mongoClient.close();

}

From source file:module.test.SearchSeries.java

License:Open Source License

public SearchSeries() throws ParseException {

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

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

    String[] listSeries = { "E-MTAB-365", "GSE3156", "GSE3744", "GSE4922", "GSE5764", "GSE6367", "GSE6883",
            "GSE8977", "GSE9014", "GSE9195", "GSE10885", "GSE11078", "GSE11352", "GSE12080", "GSE12237",
            "GSE12276", "GSE14017", "GSE16391", "GSE17215", "GSE17907", "GSE19615", "GSE21653", "GSE28681",
            "GSE38867" };

    List<Document> list = collectionSamples.find(Filters.in("_id", listSeries)).into(new ArrayList<Document>());

    Set<String> setGse = new HashSet<String>();
    List<String> listGse = new ArrayList<String>();
    for (int i = 0; i < list.size(); i++) {
        Document doc = list.get(i);
        setGse.add(doc.getString("_id"));
    }/*from  w w  w  .j  av a 2 s  .  c  o  m*/
    listGse.addAll(setGse);
    Collections.sort(listGse);

    System.out.println("Found " + list.size() + " samples");
    System.out.println("List GSE " + listGse);

    mongoClient.close();

}

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);/*from   w  ww  .j a v  a  2s  .  c om*/

        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 w  w  w. jav  a  2 s  .c  om*/

        // 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>());
    ;//  w  ww.j a v  a2  s  .  c  om

    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
 *///w w  w. j  a v a 2  s .  c om
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 ww  w  .ja v  a  2s  . com
 *            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
 *//* ww w.j ava 2 s .c om*/
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  w  w .  j a v a2s.c  o  m
}