Example usage for com.mongodb.client MongoCollection find

List of usage examples for com.mongodb.client MongoCollection find

Introduction

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

Prototype

FindIterable<TDocument> find(ClientSession clientSession);

Source Link

Document

Finds all documents in the collection.

Usage

From source file:booklistmanager.UpdateController.java

/**
 * Initializes the controller class.// ww w  .j a v a  2s . c  om
 */
@Override
public void initialize(URL url, ResourceBundle rb) {

    Connector con = new Connector();
    con.connect();
    MongoCollection<Document> col = con.getData();
    Document d = col.find(eq("bookid", index)).first();

    nameField.setText((String) d.get("Name"));
    forField.setText((String) d.get("For"));
    if (d.containsKey("Author(s)"))
        authorsField.setText((String) d.get("Author(s)"));
    if (d.containsKey("Publish date"))
        publishField.setText((String) d.get("Publish date"));
    if (d.containsKey("Edition"))
        editionField.setText((String) d.get("Edition"));

}

From source file:ch.hslu.dmg.InitDB.java

public void initVorlesungen() {
    MongoClient mongo = new MongoClient("localhost", 27017);
    MongoDatabase database = mongo.getDatabase("unidb");
    MongoCollection<Document> vorlesung = database.getCollection("vorlesungen");
    vorlesung.drop();/*from w w w .  jav  a 2  s.  c  o m*/

    ArrayList<Document> vorlesungen = new ArrayList<>();
    vorlesungen.add(new Document("VorlNr", 5001).append("Titel", "Grundzge").append("SWS", 4)
            .append("GelesenVon", 2137));
    vorlesungen.add(
            new Document("VorlNr", 5041).append("Titel", "Ethik").append("SWS", 4).append("GelesenVon", 2125));
    vorlesungen.add(new Document("VorlNr", 5043).append("Titel", "Erkentnistheorie").append("SWS", 3)
            .append("GelesenVon", 2126));
    vorlesungen.add(new Document("VorlNr", 5049).append("Titel", "Maeeutik").append("SWS", 2)
            .append("GelesenVon", 2125));
    vorlesungen.add(
            new Document("VorlNr", 4052).append("Titel", "Logik").append("SWS", 4).append("GelesenVon", 2125));
    vorlesungen.add(new Document("VorlNr", 5052).append("Titel", "Wissenschaftstheorie").append("SWS", 3)
            .append("GelesenVon", 2126));
    vorlesungen.add(new Document("VorlNr", 5216).append("Titel", "Bioethik").append("SWS", 2)
            .append("GelesenVon", 2126));
    vorlesungen.add(new Document("VorlNr", 5259).append("Titel", "Der Wiener Kreis").append("SWS", 2)
            .append("GelesenVon", 2133));
    vorlesungen.add(new Document("VorlNr", 5022).append("Titel", "Glaube und Wissen").append("SWS", 2)
            .append("GelesenVon", 2134));
    vorlesungen.add(new Document("VorlNr", 4630).append("Titel", "Die 3 Kritiken").append("SWS", 4)
            .append("GelesenVon", 2137));

    vorlesung.insertMany(vorlesungen);

    vorlesung.updateOne(eq("VorlNr", 5041), new Document("$set",
            new Document("Voraussetzung", vorlesung.find(eq("VorlNr", 5001)).iterator().next().get("_id"))));
    vorlesung.updateOne(eq("VorlNr", 5043), new Document("$set",
            new Document("Voraussetzung", vorlesung.find(eq("VorlNr", 5001)).iterator().next().get("_id"))));
    vorlesung.updateOne(eq("VorlNr", 5049), new Document("$set",
            new Document("Voraussetzung", vorlesung.find(eq("VorlNr", 5001)).iterator().next().get("_id"))));
    vorlesung.updateOne(eq("VorlNr", 5216), new Document("$set",
            new Document("Voraussetzung", vorlesung.find(eq("VorlNr", 5041)).iterator().next().get("_id"))));
    vorlesung.updateOne(eq("VorlNr", 5259), new Document("$set",
            new Document("Voraussetzung", vorlesung.find(eq("VorlNr", 5052)).iterator().next().get("_id"))));
    BasicDBList voraussetzungen = new BasicDBList();
    voraussetzungen.add(vorlesung.find(eq("VorlNr", 5043)).iterator().next().get("_id"));
    voraussetzungen.add(vorlesung.find(eq("VorlNr", 5041)).iterator().next().get("_id"));
    vorlesung.updateOne(eq("VorlNr", 5052),
            new Document("$set", new Document("Voraussetzung", voraussetzungen)));

    mongo.close();
}

From source file:cn.edu.hfut.dmic.webcollector.plugin.mongo.MongoDBManager.java

License:Open Source License

@Override
public boolean isLocked() throws Exception {
    MongoCollection lock = database.getCollection("lock");
    Document idDoc = new Document("_id", "lock");
    FindIterable<Document> findIte = lock.find(idDoc);
    Document lockDoc = findIte.first();
    if (lockDoc != null && lockDoc.getString("lock").equals("locked")) {
        return true;
    } else {/*from www  .ja va2  s.co m*/
        return false;
    }
}

From source file:cn.edu.hfut.dmic.webcollector.plugin.mongo.MongoDBUtils.java

License:Open Source License

public static void insertIfNotExists(MongoCollection col, CrawlDatum datum) {

    String key = datum.getKey();/*ww  w  .  j a v a2s.c om*/
    Document idDoc = new Document("_id", key);
    FindIterable findIte = col.find(idDoc);
    if (findIte.first() == null) {
        Document doc = CrawlDatumFormater.datumToBson(datum);
        col.insertOne(doc);
    }
}

From source file:cn.edu.hfut.dmic.webcollector.plugin.mongo.MongoDBUtils.java

License:Open Source License

public static void insertIfNotExists(MongoCollection col, Document doc) {
    String key = doc.getString("_id");
    Document idDoc = new Document("_id", key);
    FindIterable findIte = col.find(idDoc);
    if (findIte.first() == null) {
        col.insertOne(doc);//  ww  w.  ja  v  a2s  .  com
    }
}

From source file:co.aurasphere.mongodb.university.classes.m101j.homework23.MainClass.java

License:Open Source License

/**
 * The main method.//w w  w  .j a  va 2 s  .c  om
 *
 * @param args
 *            the arguments
 */
public static void main(String[] args) {

    MongoClient client = new MongoClient();
    MongoDatabase numbersDB = client.getDatabase("students");
    MongoCollection<Document> grades = numbersDB.getCollection("grades");

    // Gets all the grades.
    MongoCursor<Document> cursor = grades.find(Filters.eq("type", "homework"))
            .sort(Sorts.ascending("student_id", "score")).iterator();

    Object previousStudentId = null;
    try {
        // Finds the lowest homework score.
        while (cursor.hasNext()) {
            Document entry = cursor.next();

            // If the student_id is different from the previous one, this 
            // means that this is the student's lowest graded homework 
            // (they are sorted by score for each student).
            if (!entry.get("student_id").equals(previousStudentId)) {
                Object id = entry.get("_id");
                grades.deleteOne(Filters.eq("_id", id));

            }

            // The current document ID becomes the new previous one.   
            previousStudentId = entry.get("student_id");
        }

        // Gets the student with the highest average in the class.
        AggregateIterable<Document> results = grades
                .aggregate(Arrays.asList(Aggregates.group("$student_id", Accumulators.avg("average", "$score")),
                        Aggregates.sort(Sorts.descending("average")), Aggregates.limit(1)));

        // There should be only one result. Prints it.
        System.out.println("Solution : " + results.iterator().next().toJson());

    } finally {
        cursor.close();
    }

    client.close();
}

From source file:com.averageloser.mongodemo.Model.BookDBHelper.java

@Override
public Book getDocument(MongoCollection<Document> collection, Bson object) {
    Book book = new Book();

    Document doc = (Document) object;

    FindIterable<Document> iterable = collection.find(doc);
    iterable.forEach(new Block<Document>() {
        @Override/*from   www  . j a v a  2s .  c o  m*/
        public void apply(Document t) {
            book.setTitle(t.getString("title"));
            book.setDescription(t.getString("description"));
            book.setAuthor(t.getString("author"));
            book.setPublisher(t.getString("publisher"));
        }

    });

    return book;
}

From source file:com.bc.fiduceo.db.MongoDbDriver.java

License:Open Source License

@Override
public List<SatelliteObservation> get(QueryParameter parameter) throws SQLException {
    final MongoCollection<Document> observationCollection = database.getCollection(SATELLITE_DATA_COLLECTION);
    final List<SatelliteObservation> resultList = new ArrayList<>();

    final Document queryDocument = createQueryDocument(parameter);
    final FindIterable<Document> documents = observationCollection.find(queryDocument);
    for (Document document : documents) {
        final SatelliteObservation satelliteObservation = getSatelliteObservation(document);
        resultList.add(satelliteObservation);
    }//from  ww w  .  j  a  v a  2s  .c o  m
    return resultList;
}

From source file:com.bluedragon.mongo.MongoCollectionFind.java

License:Open Source License

public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {
    MongoDatabase db = getMongoDatabase(_session, argStruct);

    String collection = getNamedStringParam(argStruct, "collection", null);
    if (collection == null)
        throwException(_session, "please specify a collection");

    cfData query = getNamedParam(argStruct, "query", null);
    if (query == null)
        throwException(_session, "please specify query");

    int size = getNamedIntParam(argStruct, "size", -1);
    int skip = getNamedIntParam(argStruct, "skip", -1);
    cfData sort = getNamedParam(argStruct, "sort", null);
    cfData fields = getNamedParam(argStruct, "fields", null);

    try {//  w w w  .j a  v a2s  .c om
        MongoCollection<Document> col = db.getCollection(collection);

        // Get the initial cursor
        FindIterable<Document> cursor;
        long start = System.currentTimeMillis();
        Document qry = getDocument(query);

        cursor = col.find(qry);

        if (fields != null)
            cursor = cursor.projection(getDocument(fields));

        // Are we sorting?
        if (sort != null)
            cursor = cursor.sort(getDocument(sort));

        // Are we limiting
        if (skip != -1)
            cursor = cursor.skip(skip);

        // How many we bringing back
        if (size != -1)
            cursor = cursor.limit(size);

        // Now we can run the query
        cfArrayData results = cfArrayData.createArray(1);

        cursor.forEach(new Block<Document>() {

            @SuppressWarnings("rawtypes")
            @Override
            public void apply(final Document st) {
                try {
                    results.addElement(tagUtils.convertToCfData((Map) st));
                } catch (cfmRunTimeException e) {
                }
            }
        });

        _session.getDebugRecorder().execMongo(col, "find", qry, System.currentTimeMillis() - start);

        return results;
    } catch (MongoException me) {
        throwException(_session, me.getMessage());
        return null;
    }
}

From source file:com.bluedragon.mongo.MongoCollectionFindOne.java

License:Open Source License

@SuppressWarnings("rawtypes")
public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {
    MongoDatabase db = getMongoDatabase(_session, argStruct);

    String collection = getNamedStringParam(argStruct, "collection", null);
    if (collection == null)
        throwException(_session, "please specify a collection");

    cfData query = getNamedParam(argStruct, "query", null);
    if (query == null)
        throwException(_session, "please specify query to find");

    cfData fields = getNamedParam(argStruct, "fields", null);

    try {/* w w w. j a  v a2 s  . c  o m*/
        MongoCollection<Document> col = db.getCollection(collection);

        long start = System.currentTimeMillis();
        Document qry = getDocument(query);

        FindIterable<Document> cursor = col.find(qry).limit(1);

        if (fields != null)
            cursor = cursor.projection(getDocument(fields));

        _session.getDebugRecorder().execMongo(col, "findone", qry, System.currentTimeMillis() - start);
        return tagUtils.convertToCfData((Map) cursor.first());

    } catch (MongoException me) {
        throwException(_session, me.getMessage());
        return null;
    }
}