how to call count operation after find with mongodb java driver

ⅰ亾dé卋堺 提交于 2019-12-04 23:07:38

As you said the MongoCollection has the count() method that will return the number of documents in the collection, but it has also a count(Bson filter) that will return the number of documents in the collection according to the given options.

So you can just use:

long count = photosCollections.count(Document.parse("{_id : {$lt : 100}}"))

or maybe clearer:

Document query = new Document("_id", new Document("$lt", 100));
long count = photosCollections.count(query);

ref: http://api.mongodb.com/java/3.3/com/mongodb/client/MongoCollection.html#count-org.bson.conversions.Bson-

I had a similar problem. I am using MongoCollection instead of DBCollection, as it is what it is used in MongoDG 3.2 guide. MongoCollection hasn't got count() method, so I think the only option is to use the iterator to count them.

In my case I only needed to know if any document has been returned, I am using this:

if(result.first() != null)
Bson bson = Filters.eq("type", "work");
List<Document> list = collection.find(bson).into(new ArrayList<>());
System.out.println(list.size());

into(A) (A is collection type) method iterates over all the documents and adds each to the given target. Then we can get the count of the returned documents.

In MongoDB 3.4 you can only use the Iterator of FindIterable to get the count of the documents returned by a filter. e.g.

`FindIterable findIterable = 
 mongoCollection.find(Filters.eq("EVENT_TYPE", "Sport"));
    Iterator iterator = findIterable.iterator();
    int count = 0;
    while (iterator.hasNext()) {
        iterator.next();
        count++;
    }
    System.out.println(">>>>> count = " + count);

`

The API docs clearly state that DBCursor Object provides a count method:

MongoClient client = new MongoClient(MONGOHOST,MONGOPORT);
DBCollection coll = client.getDB(DBNAME).getCollection(COLLECTION);

DBObject query = new Querybuilder().start()
                  .put("_id").lessThan(100).get();

DBCursor result = coll.find(query);

System.out.println("Number of pictures found: " + result.count() );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!