Docs 菜单
Docs 主页
/ /
Tutorials
/ / /

运行命令

并非所有数据库命令都有特定的辅助方法。 但是,您可以使用 MongoDatabase.runCommand()方法运行任何 MongoDB 命令。

要学习;了解有关MongoDB命令的更多信息,请参阅服务器手册中的数据库命令

您必须设置以下组件才能运行本指南中的代码示例:

import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoDatabase;
import org.bson.Document;

重要

本指南使用Subscriber实现,如快速入门入门知识中所述。

首先,连接到 MongoDB 部署,然后声明并定义一个MongoDatabase实例。

以下代码连接到在端口27017上的localhost上运行的独立 MongoDB 部署。 然后,它定义database变量以引用test数据库:

MongoClient mongoClient = MongoClients.create();
MongoDatabase database = mongoClient.getDatabase("test");

要了解有关连接到 MongoDB 部署的更多信息,请参阅连接到 MongoDB教程。

要运行buildInfo命令,请构造一个指定该命令的Document对象,并将其作为参数传递给runCommand()方法。

以下示例代码运行buildInfo命令并打印结果:

database.runCommand(new Document("buildInfo", 1)).subscribe(new PrintDocumentSubscriber());

后退

GridFS

在此页面上