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();

Source Link

Document

Finds all documents in the collection.

Usage

From source file:mongoSample.MongoSample.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args//from  www.ja va2 s  .co 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();/*  ww  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: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  a  2 s .  c o  m
    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:net.es.netshell.mongodb.MongoDBProvider.java

License:Open Source License

@Override
public final List<String> find(String user, String name, Map<String, Object> query)
        throws InstantiationException {
    String collectionName = user + "_" + name;
    MongoCollection collection = this.db.getCollection(collectionName);
    if (collection == null) {
        throw new RuntimeErrorException(new Error("Could not create collection " + collectionName));
    }/*  ww w. j  a  v  a2  s . c  om*/
    ArrayList<String> res = new ArrayList<String>();
    FindIterable<Document> results = null;

    if (query == null) {
        results = collection.find();
    } else {
        Document queryDocument = new Document(query);
        results = collection.find(queryDocument);
    }
    for (Document doc : results) {
        doc.remove("_id");
        res.add(doc.toJson());
    }
    return res;
}

From source file:net.netzgut.integral.mongo.internal.services.MongoODMImplementation.java

License:Apache License

@Override
public <T extends Serializable> Stream<T> findAll(Class<T> entityClass) {
    MongoCollection<Document> collection = this.mongo.getCollection(entityClass);
    FindIterable<Document> find = collection.find();
    return this.converter.entitiesStreamFrom(find, entityClass);
}

From source file:net.ymate.platform.persistence.mongodb.impl.MongoSession.java

License:Apache License

public <T extends IEntity> IResultSet<T> find(Class<T> entity, OrderBy orderBy, Page page) throws Exception {
    MongoCollection<Document> _collection = __doGetCollection(entity);
    FindIterable<Document> _findIterable = _collection.find();
    if (orderBy != null) {
        _findIterable.sort(orderBy.toBson());
    }/* w ww.j  a va2  s  .  com*/
    long _recordCount = 0;
    if (__doPageInit(_findIterable, page)) {
        _recordCount = _collection.count();
    }
    return new DefaultResultSet<T>(ResultSetHelper.toEntities(entity, _findIterable), page.page(),
            page.pageSize(), _recordCount);
}

From source file:nl.mvdb.mongodb.RemoveStudentsLowestHomeworkScore.java

License:Apache License

public static void main(String[] args) {
    MongoClient client = new MongoClient();
    try {//  w w  w.  ja v a  2  s .c om
        MongoDatabase database = client.getDatabase("school");
        MongoCollection<Document> collection = database.getCollection("students");

        MongoCursor<Document> iterator = collection.find().sort(ascending("scores.score")).iterator();

        while (iterator.hasNext()) {
            Document studentDoc = iterator.next();
            System.out.println(studentDoc);

            Document lowestScoreDoc = null;

            List<Document> scoreDocs = (ArrayList) studentDoc.get("scores");
            for (Document scoreDoc : scoreDocs) {
                if ("homework".equals(scoreDoc.getString("type"))) {
                    Double score = scoreDoc.getDouble("score");
                    if (lowestScoreDoc == null || score < lowestScoreDoc.getDouble("score")) {
                        lowestScoreDoc = scoreDoc;
                    }
                }
            }

            if (lowestScoreDoc != null) {
                scoreDocs.remove(lowestScoreDoc);
                studentDoc.put("scores", scoreDocs);
                collection.replaceOne(new Document("_id", studentDoc.getInteger("_id")), studentDoc);
            }

        }

        System.out.println(collection.count());
    } finally {
        client.close();
    }
}

From source file:nl.mvdb.mongodb.RemoveStudentsLowestScore.java

License:Apache License

public static void main(String[] args) {
    MongoClient client = new MongoClient();
    try {/* w ww  .j av a 2 s .  c o m*/
        MongoDatabase database = client.getDatabase("students");
        MongoCollection<Document> collection = database.getCollection("grades");

        MongoCursor<Document> iterator = collection.find().sort(ascending("student_id", "score")).iterator();

        Integer lastStudentId = null;
        while (iterator.hasNext()) {
            Document gradingDoc = iterator.next();
            Integer studentId = gradingDoc.getInteger("student_id");
            if (!studentId.equals(lastStudentId)) {
                lastStudentId = studentId;
                System.out.println(lastStudentId);
                collection.deleteOne(gradingDoc);
            }
        }

        System.out.println(collection.count());
    } finally {
        client.close();
    }
}

From source file:org.apache.beam.sdk.io.mongodb.FindQuery.java

License:Apache License

@Override
public MongoCursor<Document> apply(MongoCollection<Document> collection) {
    return collection.find().filter(filters()).limit(limit()).projection(Projections.include(projection()))
            .iterator();/*from   w w w .  j  a v  a2s  .  c  om*/
}

From source file:org.apache.drill.exec.store.mongo.MongoGroupScan.java

License:Apache License

@Override
public ScanStats getScanStats() {
    try {/*from   ww w .  j  a  v  a  2  s  .co  m*/
        MongoClient client = storagePlugin.getClient();
        MongoDatabase db = client.getDatabase(scanSpec.getDbName());
        MongoCollection<Document> collection = db.getCollection(scanSpec.getCollectionName());
        long numDocs = collection.count();
        float approxDiskCost = 0;
        if (numDocs != 0) {
            String json = collection.find().first().toJson();
            approxDiskCost = json.getBytes().length * numDocs;
        }
        return new ScanStats(GroupScanProperty.EXACT_ROW_COUNT, numDocs, 1, approxDiskCost);
    } catch (Exception e) {
        throw new DrillRuntimeException(e.getMessage(), e);
    }
}