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:mongodb_teste.MongoDB_teste.java

/**
 * @param args the command line arguments
 *//*from ww w.  j a v  a 2  s .  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:mongome.MongoWriter.java

public void addUsers(ArrayList<User> usersList) {

    try {/*w w  w  .jav a2s .  co  m*/
        MongoDatabase db = mongoClient.getDatabase("reserva_bilhetes");
        System.out.println(">> Database connection sucessful!");

        MongoCollection col = db.getCollection("utilizadores");

        for (User usr : usersList) {
            Document doc = new Document();
            doc.put("_id", usr.getUsername());
            doc.put("nome", usr.getNome());
            doc.put("password", usr.getPassword());
            doc.put("email", usr.getEmail());
            doc.put("nif", usr.getNIF());
            doc.put("morada", usr.getMorada());

            col.insertOne(doc);
            System.out.println("User " + usr.getNome() + " added!");

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

}

From source file:mongome.MongoWriter.java

public void addReserva(ArrayList<Reserva> reservaList) {

    try {/*from w w  w.jav a 2s. c  o m*/
        MongoDatabase db = mongoClient.getDatabase("reserva_bilhetes");
        System.out.println(">> Database connection sucessful!");

        MongoCollection col = db.getCollection("reservas");

        for (Reserva r : reservaList) {
            Document doc = new Document();
            doc.put("_id", r.getId());
            doc.put("username", r.getUsername());
            doc.put("data_reserva", r.getDataRes());
            doc.put("id_comboio", r.getIdComboio());
            doc.put("preco", r.getPreco());
            doc.put("origem", r.getOrigem());
            doc.put("destino", r.getDestino());
            doc.put("horaPartida", r.getHoraPartida());
            doc.put("horaChegada", r.getHoraChegada());
            List<BasicDBObject> lugares = new ArrayList<>();

            for (Seat s : r.getLugares()) {
                BasicDBObject tmp = new BasicDBObject();
                tmp.put("numero", s.getNumero());
                tmp.put("carruagem", s.getCarruagem());
                tmp.put("classe", s.getClasse());
                lugares.add(tmp);
            }
            doc.put("lugares", lugares);

            if (doc != null)
                col.insertOne(doc);
            System.out.println("Reserva " + r.getId() + " added!");

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

}

From source file:mongome.MongoWriter.java

public void addComboios(ArrayList<Train> trainList) {

    try {//from  w w  w  .  j a  v  a 2 s . com
        MongoDatabase db = mongoClient.getDatabase("reserva_bilhetes");
        System.out.println(">> Database connection sucessful!");

        MongoCollection col = db.getCollection("comboios");

        for (Train t : trainList) {
            Document doc = new Document();
            doc.put("_id", t.getId_Comboio());
            doc.put("lotaco", t.getLotacao());
            doc.put("nome", t.getNome());

            List<BasicDBObject> lugares = new ArrayList<>();
            for (Seat s : t.getLugares()) {
                BasicDBObject tmp = new BasicDBObject();
                tmp.put("numero", s.getNumero());
                tmp.put("carruagem", s.getCarruagem());
                tmp.put("classe", s.getClasse());
                lugares.add(tmp);
            }
            doc.put("lugares", lugares);

            if (doc != null)
                col.insertOne(doc);
            System.out.println("Comboio " + t.getNome() + " added!");

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

}

From source file:mongoSample.MongoSample.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args//w  w w  .  j a  v  a2 s  .  c  o  m
 *            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 w  w w  . j a v a 2  s . 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:mp6uf2pt3.MP6UF2PT3.java

/**
 * @param args the command line arguments
 *//*from w  ww . ja  v a 2s  . 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();//from   w  ww.  j a v a2 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()));
                }
            }
        }

    }
}

From source file:mx.com.tecnomotum.testmongodb.Principal.java

public static void main(String args[]) {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase db = mongoClient.getDatabase("test");
    MongoCollection<Document> coleccion = db.getCollection("restaurants");
    long totalElementos = coleccion.count();
    System.out.println("Total de elementos en la coleccin:" + totalElementos);

    // Obtener el primer elemento de la coleccin
    Document myDoc = coleccion.find().first();
    System.out.println("Primer object:" + myDoc.toJson());

    //Crear y aadir un nuevo documento a la coleccin
    Document nuevoDoc = new Document("name", "CARLITOS buf");
    nuevoDoc.append("borough", "Elvia");
    nuevoDoc.append("cuisine", "Gourmet");
    List<Document> puntuaciones = new ArrayList<>();
    Document punt = new Document();
    punt.append("grade", "A");
    punt.append("date", new Date());
    punt.append("score", 9);
    puntuaciones.add(punt);//from  www .j av a2s.  com
    nuevoDoc.append("grades", puntuaciones);
    coleccion.insertOne(nuevoDoc);
    System.out.println("Total de elementos en la coleccin:" + coleccion.count());

    //OBtener un objeto de una coleccin
    Document objetoResp = coleccion.find(eq("name", "CARLITOS buf")).first();
    System.out.println("OBjeto encontrado:" + objetoResp.toJson());

    //OBtener la proyeccin del documento
    Document objetoResp2 = coleccion.find(eq("name", "CARLITOS buf"))
            .projection(fields(excludeId(), include("name"), include("grades.score"))).first();
    System.out.println("OBjeto encontrado:" + objetoResp2.toJson());

    //OBtener conjuntos de datos
    Block<Document> printBlock = new Block<Document>() {

        @Override
        public void apply(final Document doc) {
            System.out.println(doc.toJson());
        }
    };

    coleccion.find(eq("cuisine", "Hamburgers")).projection(fields(excludeId(), include("name")))
            .sort(Sorts.ascending("name")).forEach(printBlock);

}

From source file:MyLibrary.DoMongodb.java

/**
 * mongodb//w ww  .ja va  2s. c o  m
 * @param MongoDatabase1 MongoDatabase
 * @param collections collections
 * @param JsonObject1 JsonObject
 * @return null
 */
public String insert(MongoDatabase MongoDatabase1, String collections, JSONObject JsonObject1) {
    String result = null;
    Document Document1 = new Document();
    try {
        Document1 = JsonToDocument(JsonObject1);
        MongoDatabase1.getCollection(collections).insertOne(Document1);
    } catch (Exception e) {
        result = e.getMessage();
    }
    return result;
}