文档菜单
文档首页
/ / /
Java 同步驱动程序
/

运行命令

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

重要

优先使用驱动程序方法而非数据库命令

驱动程序为许多数据库命令提供了包装方法。我们建议在可能的情况下使用驱动程序方法而不是执行数据库命令。

要执行管理任务,请使用MongoDB Shell 而不是 Java 驱动程序。在 shell 中调用 db.runCommand() 方法是发布数据库命令的首选方式,因为它在 shell 和驱动程序之间提供了统一的接口。

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

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

注意

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

// Runs a database command by using the Java driver
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));
// Retrieves statistics about the specified database
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}

提示

旧版 API

如果您正在使用旧版 API,请参阅我们的常见问题解答页面了解您需要对此代码示例进行哪些更改。

有关本页面上提到的类和方法的更多信息,请参阅以下资源

返回

不同的字段值