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: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  a v  a2  s  .  c om
    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 w w  w  .  ja v a  2  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  w w  . jav  a  2  s .  co m*/
}

From source file:mongodb_teste.MongoDB_teste.java

/**
 * @param args the command line arguments
 *//*  ww  w .  j av  a2s.  co  m*/
public static void teste(String[] args) throws ParseException {
    // TODO code application logic here
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase("BDprject");
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
    /*db.getCollection("Professores").insertOne(
    new Document("nome", "Lana")
        .append("email", "123@ufu.com")
        .append("materias", asList(
                new Document()
                        .append("nome", "EDG")
                        .append("nota", "B"),
                new Document()
                        .append("nome", "BD")
                        .append("nota", "B")))
        .append("telefone", "435341543"));*/
    Iterable<Document> iterable = db.getCollection("Professores")
            .aggregate(Arrays.asList((Aggregates.match(new Document("nome", "Miguel"))),
                    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()) {
        System.out.println(it.next().get("_id"));
    }
}

From source file:mongofx.service.MongoDatabase.java

License:Open Source License

public MongoDatabase(MongoClient client, String name) {
    this.client = client;
    mongoDb = client.getDatabase(name);
}

From source file:mongoSample.MongoSample.java

License:Apache License

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

    MongoClient mongoClient = new MongoClient(mongoServer);
    MongoDatabase database = mongoClient.getDatabase("sakila");
    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);
    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:mongoSample.MyMongoDemo.java

License:Apache License

public static void main(final String[] args) {
    String mongoServer = args[0];

    MongoClient mongoClient = new MongoClient(mongoServer);
    MongoDatabase database = mongoClient.getDatabase("NGDBDemo");
    MongoCollection<Document> collection = database.getCollection("test");

    collection.drop();//from  ww  w. j a  va  2s  .c  o m

    Document people = new Document(); // A document for a person
    people.put("Name", "Guy");
    people.put("Email", "guy@gmail.com");

    BasicDBList friendList = new BasicDBList(); // A list for the persons
    // friends

    BasicDBObject friendDoc = new BasicDBObject(); // A document for each
    // friend

    friendDoc.put("Name", "Jo");
    friendDoc.put("Email", "Jo@gmail.com");
    friendList.add(friendDoc);
    friendDoc.clear();
    friendDoc.put("Name", "John");
    friendDoc.put("Email", "john@gmail.com");
    friendList.add(friendDoc);
    people.put("Friends", friendDoc);

    collection.insertOne(people);

    System.out.println('1');
    MongoCursor<Document> cursor = collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }
    System.out.println('2');

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

    System.out.println('3');
    // now use a query to get 1 document out
    Document myDoc = collection.find(eq("Name", "Guy")).first();
    System.out.println(myDoc.toJson());

    database = mongoClient.getDatabase("sakila");
    collection = database.getCollection("films");
    for (Document cur : collection.find()) {
        System.out.println(cur.toJson());
    }
    mongoClient.close();
}

From source file:mongotwitter.MongoTwitter.java

public MongoTwitter() {
    String url = "mongodb://" + address;
    MongoClientURI uri = new MongoClientURI(url);
    MongoClient mc = new MongoClient(uri);
    db = mc.getDatabase(database);
}

From source file:mp6uf2pt3.MP6UF2PT3.java

/**
 * @param args the command line arguments
 *///from www. ja va 2 s .  c om
public static void main(String[] args) {

    MongoClient mongoClient = new MongoClient();
    MongoDatabase database = mongoClient.getDatabase("consultes");

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

    MongoCollection<Document> col = database.getCollection("restaurants");

}

From source file:MultiSources.Fusionner.java

public void exportAllCandsMongoDB(ArrayList<NodeCandidate> allCands) {
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase("evals_Triticum");
    db.drop();//  w ww .  j a v a  2  s.  com
    MongoCollection<Document> collection = db.getCollection("triticumCandidate");
    MongoCollection<Document> collectionRel = db.getCollection("triticumICHR");
    MongoCollection<Document> collectionType = db.getCollection("triticumTypeCandidate");
    MongoCollection<Document> collectionLabel = db.getCollection("triticumLabelCandidate");
    for (NodeCandidate nc : allCands) {
        if (nc.isIndividual()) {
            collection.insertOne(new Document(nc.toDBObject()));
            IndividualCandidate ic = (IndividualCandidate) nc;
            for (ArcCandidate ac : ic.getAllArcCandidates()) {
                String prop = ac.getDataProp();
                if (prop.startsWith("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")) {
                    collectionType.insertOne(new Document(ac.toDBObject()));
                } else if (prop.startsWith("http://ontology.irstea.fr/AgronomicTaxon#hasHigherRank")) {
                    collectionRel.insertOne(new Document(ac.toDBObject()));
                }
                for (LabelCandidate lc : ic.getLabelCandidates()) {
                    collectionLabel.insertOne(new Document(lc.toDBObject()));
                }
            }
        }

    }
}