Docs 菜单

Docs 主页开发应用程序MongoDB 驱动程序Java (Sync) 驱动程序

运行命令

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

重要

首选驱动程序方法而非数据库命令

驱动程序为许多数据库命令提供了封装方法。我们建议尽可能使用驱动程序方法,而不是执行数据库命令。

要执行管理任务,请使用 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,请参阅我们的常见问题页面,了解需要对该代码示例进行哪些更改。

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

← 检索字段的不同值