如何使用MongoClient类从Mongo Java驱动程序调用db.Collection.stats() [英] How to call db.Collection.stats() from Mongo java driver using MongoClient class
问题描述
我正在使用这种依赖关系.
I am using this dependency.
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.12.2</version>
</dependency>
包装:
打包com.mongodb.MongoClient;
如何按名称获取收藏集,然后获取其状态,以便可以使用以下信息:
How can I get collection by name then get its status so that the following information will be available:
- 大小
- storageSize
看来,此的答案从Mongo Java驱动程序调用db.Collection.stats()使用已弃用的类 package com.mongodb;
It seems that the answer for this How to call db.Collection.stats() from Mongo java driver uses deprecated class 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:
This is using the MongoDB Java driver version 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
对象释放与连接相关的资源后,它将关闭.
Note the usage of the try-with-resources
clause; it closes the MongoClient
object after its use to release the connection related resources.
这篇关于如何使用MongoClient类从Mongo Java驱动程序调用db.Collection.stats()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!