Example usage for com.mongodb.client MongoCollection count

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

Introduction

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

Prototype

@Deprecated
long count();

Source Link

Document

Counts the number of documents in the collection.

Usage

From source file:database.BFIdataTable.java

public int getIndex() {
    Document doc = new Document();
    MongoCollection<Document> col = db.getCollection(col_name);
    if (col.count() <= 0)
        return 1;
    for (Document d : col.find())
        doc = d;/*from   w  ww  .  ja va2 s. c o m*/
    int j = (int) doc.get("dataid");
    return j + 1;
}

From source file:examples.tour.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
 *//*from w  w w  .  j av a2s.  c  om*/
public static void main(final String[] args) {
    MongoClient mongoClient;

    if (args.length == 0) {
        // connect to the local database server
        mongoClient = new MongoClient();
    } else {
        mongoClient = new MongoClient(new MongoClientURI(args[0]));
    }

    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb");

    // 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>() {

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

    // Aggregation
    collection
            .aggregate(
                    asList(match(gt("i", 0)), project(Document.parse("{ITimes10: {$multiply: ['$i', 10]}}"))))
            .forEach(printBlock);

    myDoc = collection.aggregate(singletonList(group(null, sum("total", "$i")))).first();
    System.out.println(myDoc.toJson());

    // Update One
    collection.updateOne(eq("i", 10), set("i", 110));

    // Update Many
    UpdateResult updateResult = collection.updateMany(lt("i", 100), inc("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:it.av.fac.datasources.wikipedia.WikipediaSource.java

public WikipediaSource(String XMLFilePath) throws ParserConfigurationException, SAXException {
    this.parser = SAXParserFactory.newInstance().newSAXParser();
    this.fac = new APIClient("http://localhost:8080/FAC_Webserver");
    this.XMLFilePath = XMLFilePath;

    try (MongoClient mongoClient = new MongoClient("127.0.0.1", 27017)) {
        MongoDatabase mongoDB = mongoClient.getDatabase("fac");
        MongoCollection metadataCol = mongoDB.getCollection("metadata");
        this.SKIP = metadataCol.count();
    }//w w  w.ja v a  2 s  . c o m
}

From source file:it.terrinoni.Question.java

public static void main(String[] args) {
    MongoClient c = new MongoClient();
    MongoDatabase db = c.getDatabase("test");
    MongoCollection<Document> animals = db.getCollection("animals");

    Document animal = new Document("animal", "monkey");

    animals.insertOne(animal);//from   ww  w .j  a  va 2  s.c om

    animal.remove("animal");
    animal.append("animal", "cat");
    try {
        animals.insertOne(animal);
    } catch (MongoWriteException ex) {
        System.err.println(animal.getString("animal") + " not inserted");
    }

    animal.remove("animal");
    animal.append("animal", "lion");
    try {
        animals.insertOne(animal);
    } catch (MongoWriteException ex) {
        System.err.println(animal.getString("animal") + " not inserted");
    }

    long tot = animals.count();

    System.out.println("Total number of inserted animals: " + tot);
}

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  av  a  2s.  c o m*/
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:mongoSample.MongoSample.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args//from  ww w.j  a v a 2  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: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);//w  w  w .  j ava2 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.netzgut.integral.mongo.internal.services.MongoODMImplementation.java

License:Apache License

@Override
public <T extends Serializable> long count(Class<T> entityClass) {
    MongoCollection<Document> collection = this.mongo.getCollection(entityClass);
    return collection.count();
}

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());
    }/*from  w ww.  ja  v a  2s .  c  o  m*/
    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  ww .  j  a  v  a 2  s  .  co  m
        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();
    }
}