【问题标题】:How I can count documents in collection MongoDB Java? [duplicate]如何计算 MongoDB Java 集合中的文档? [复制]
【发布时间】:2021-02-14 10:24:39
【问题描述】:

我收藏了很多文件 那么,我如何计算集合中的文档

【问题讨论】:

    标签: java mongodb mongodb-java


    【解决方案1】:
    1. 获取集合的MongoCollectionDBCollection 实例。例如:

       MongoClient mongoClient = new MongoClient(
               new ServerAddress("localhost", 27017));
       DB db = mongoClient.getDB("mydb");
       DBCollection collection = db.getCollection("test"); 
      
    2. 在集合对象上调用count() 方法。


    显然,以上是针对 MongoDB 3.x 驱动程序 API 的。

    如果您使用的是 MongoDB 4.x API,您应该使用MongoCollection 接口提供的countDocuments() 方法。像这样。

    MongoClient  mongoClient = MongoClients.create(...);
    MongoCollection collection = mongoClient.getCollection("test"); \
    
    long count = collection.countDocuments();
    

    (现在将 3.x API 描述为“遗留”API。但是,我在 MongoDB 文档中看不到任何内容表明它们实际上已被弃用。如果有人能找到说明这一点的内容,请发布 URL下面。)

    【讨论】:

    • 在较新版本的 MongoDB 和 Java 驱动程序中,count 方法已弃用。相反,请使用countDocuments
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-21
    相关资源
    最近更新 更多