Docs 菜单
Docs 主页
/ / /
java sync
/

运行命令

您可以使用 MongoDatabase.runCommand() 方法运行所有原始数据库操作。原始数据库操作是可以在 MongoDB Server CLI 上直接执行的命令。这些命令包括管理和诊断任务,如获取服务器统计数据或初始化副本集。在 MongoDatabase 的实例上调用带有 Bson 命令对象的 runCommand() 方法,运行原始数据库操作。

提示

尽可能使用 MongoDB Shell 而不是 Java 驱动程序来执行管理任务,因为使用 Shell 实现这些任务通常比在 Java 应用程序中更快、更容易。

runCommand() 方法接受 Bson 对象形式的命令。默认情况下,runCommand 返回类型为 org.bson.Document 的对象,其中包含数据库命令的输出结果。作为可选的第二个参数,您可以指定 runCommand() 的返回类型。

在以下样本代码中,我们发送 dbStats 命令以请求特定 MongoDB 数据库的统计信息。

注意

此示例使用连接 URI 连接到 MongoDB 实例。要了解有关连接到 MongoDB 实例的更多信息,请参阅连接指南。

package usage.examples;
import org.bson.BsonDocument;
import org.bson.BsonInt64;
import org.bson.Document;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import org.bson.conversions.Bson;
public class RunCommand {
public static void main(String[] args) {
// Replace the uri string with your MongoDB deployment's connection string
String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
try {
Bson command = new BsonDocument("dbStats", new BsonInt64(1));
Document commandResult = database.runCommand(command);
// Prints the database statistics
System.out.println("dbStats: " + commandResult.toJson());
} catch (MongoException me) {
// Prints a message if any exceptions occur during the command execution
System.err.println("An error occurred: " + me);
}
}
}
}

运行上述命令后,您将看到与下面类似的输出结果:

dbStats: {"db": "sample_mflix", "collections": 5, "views": 0, "objects": 75595, "avgObjSize": 692.1003770090614, "dataSize": 52319328, "storageSize": 29831168, "numExtents": 0, "indexes": 9, "indexSize": 14430208, "fileSize": 0, "nsSizeMB": 0, "ok": 1}

提示

Legacy API

如果您使用的是传统 API,请参阅我们的常见问题页面,了解需要对该代码示例进行哪些更改。

有关此页面上所提及的类和方法的更多信息,请参阅以下资源:

  • runCommand() API 文档

  • 数据库命令服务器手册条目

  • dbStats 服务器手册条目

后退

检索字段的不同值