【问题标题】:how to call count operation after find with mongodb java driver使用mongodb java驱动程序查找后如何调用计数操作
【发布时间】:2015-12-17 11:00:44
【问题描述】:

我正在使用 MongoDB 3.0。假设有一组名为photos的文档,其结构为

{"_id" : 1, photographer: "jack"}

使用database.getCollection("photos"),Mongodb 将返回一个MongoCollection 对象,我有方法count() 来获取返回的文档数。

但是,当我使用特定条件进行查询时。例如查找 id 小于 100 的文档:

photosCollections.find(Document.parse("{_id : {$lt : 100}}"))

以上find 方法将始终返回一个不提供count() 函数的游标。那么我怎么知道返回了多少文件呢?我知道在命令行上,我可以使用

db.photos.find({_id : {$lt : 100}}).count()

当然,我可以通过迭代器,自己统计文档的数量。但是我觉得它真的很笨拙。我想知道 MongoDB java 驱动程序是否提供这样的功能来计算 find() 方法返回的文档数?如果不是,这个决定背后的原因是什么?

【问题讨论】:

    标签: mongodb mongodb-java


    【解决方案1】:

    正如您所说,MongoCollection 具有 count() 方法,该方法将返回集合中的文档数,但它也有一个 count(Bson filter) 将返回集合中的文档数根据给定选项

    所以你可以使用:

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

    或者更清楚:

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

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

    【讨论】:

    【解决方案2】:

    在 MongoDB 3.4 中,您只能使用 FindIterable 的 Iterator 来获取过滤器返回的文档数。例如

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

    `

    【讨论】:

      【解决方案3】:

      我遇到了类似的问题。我使用的是 MongoCollection 而不是 DBCollection,因为它在 MongoDG 3.2 指南中使用。 MongoCollection 没有 count() 方法,所以我认为唯一的选择是使用迭代器来计算它们。

      就我而言,我只需要知道是否有任何文件被退回,我正在使用这个:

      if(result.first() != null)
      

      【讨论】:

        【解决方案4】:
        Bson bson = Filters.eq("type", "work");
        List<Document> list = collection.find(bson).into(new ArrayList<>());
        System.out.println(list.size());
        

        into(A) (A 是集合类型)方法迭代所有文档并将每个文档添加到给定目标。然后我们可以得到返回文档的计数。

        【讨论】:

          【解决方案5】:

          API 文档明确指出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() );
          

          【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-10-24
          • 1970-01-01
          • 1970-01-01
          • 2019-11-03
          • 1970-01-01
          • 2012-05-24
          • 1970-01-01
          相关资源
          最近更新 更多