Overview
在本指南中,您可以学习;了解如何使用Java Reactive Streams驾驶员运行数据库命令。 您可以使用数据库命令执行各种管理和诊断任务,例如获取服务器统计信息、初始化副本集或运行聚合管道。
提示
优先使用驱动程序方法而非数据库命令
驾驶员为许多数据库命令提供了方法。 我们建议尽可能使用驾驶员方法,而不是执行数据库命令。
要执行管理任务,请使用 MongoDB Shell而不是Java Reactive Streams驾驶员。 调用MongoDB Shell db.runCommand()方法是发出数据库命令的首选方法,因为它在shell和驱动程序之间提供了一致的接口。
重要
项目 Reactor 库
This guide uses the Project Reactor library to consume Publisher
instances returned by the Java Reactive Streams driver methods. To learn more about the Project Reactor library and how to use it, see Getting Started in the Reactor documentation. To learn more about how we use Project Reactor library methods in this guide, see the Write Data to MongoDB guide.
运行命令
要运行数据库命令,请在文档中指定该命令,然后将该文档传递给runCommand()
方法。 以下代码对数据库调用runCommand()
方法来运行ping
命令,这是一个无操作命令,用于测试服务器是否有响应。
Document command = new Document("ping", 1); Publisher<Document> commandPublisher = database.runCommand(command); Document result = Mono.from(commandPublisher).block(); System.out.println(result);
Document{{ok=1}}
更多信息
要查看数据库命令及其可用参数的完整列表,请参阅MongoDB Server手册中的数据库命令。
API 文档
To learn more about the runCommand()
method, see the runCommand() API documentation.