java - 如何使用 MongoClient 类从 Mongo java 驱动程序调用 db.Collection.stats()

标签 java mongodb mongo-java-driver

我正在使用此依赖项。

        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver</artifactId>
            <version>3.12.2</version>
        </dependency>

封装:

包 com.mongodb.MongoClient;

如何按名称获取集合,然后获取其状态,以便提供以下信息:

  1. 尺寸
  2. 存储大小

Collection Status

看来这个答案How to call db.Collection.stats() from Mongo java driver使用已弃用的类 package com.mongodb;

        // Mongodb initialization parameters.
        int port_no = 27017;
        String auth_user="jcg", auth_pwd = "admin@123", host_name = "localhost", db_name = "mongoauthdemo", db_col_name = "emp", encoded_pwd = "";

        /* Imp. Note -
         *      1.  Developers will need to encode the 'auth_user' or the 'auth_pwd' string if it contains the <code>:</code> or the <code>@</code> symbol. If not, the code will throw the <code>java.lang.IllegalArgumentException</code>.
         *      2.  If the 'auth_user' or the 'auth_pwd' string does not contain the <code>:</code> or the <code>@</code> symbol, we can skip the encoding step.
         */
        try {
            encoded_pwd = URLEncoder.encode(auth_pwd, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            log.error(ex);
        }

        // Mongodb connection string.
        String client_url = "mongodb://" + auth_user + ":" + encoded_pwd + "@" + host_name + ":" + port_no + "/" + db_name;
        MongoClientURI uri = new MongoClientURI(client_url);

        // Connecting to the mongodb server using the given client uri.
        MongoClient mongo_client = new MongoClient(uri);

        // Fetching the database from the mongodb.
        MongoDatabase db = mongo_client.getDatabase(db_name);

        // Fetching the collection from the mongodb.
        MongoCollection<Document> coll = db.getCollection(db_col_name);

最佳答案

这使用的是 MongoDB Java 驱动程序版本 3.12:

try(MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017/")) {

    MongoDatabase db = mongoClient.getDatabase("test");
    Document collStatsResults = db.runCommand(new Document("collStats", "myCollection"));
    System.out.println(collStatsResults.get("size"));
    System.out.println(collStatsResults.get("storageSize"));
}

注意try-with-resources子句的用法;它在使用后关闭 MongoClient 对象以释放连接相关资源。

关于java - 如何使用 MongoClient 类从 Mongo java 驱动程序调用 db.Collection.stats(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61052446/

相关文章:

java - 简单的 Jdbc 模板。 - 插入和检索 ID

ruby-on-rails - 想要将 "acts-as-taggable-on"用于 mongoid

mongodb - 对象 ID 中的负进程 ID

java - mongo Java 通过数组搜索

java - Mongo Java 驱动程序 3.6.1 - 如何将 json 数组结构化字符串解析为 BasicDBList

java - 使用Jena编写JSON-LD

javascript - 带有 JavaScript 警报/提示的 Android WebViewClient

java - 如何从 Android 应用程序中的异步任务返回位图

MongoDB 聚合填充缺失天数

javascript - Mongo 客户端无法访问带有下划线前缀的集合