Docs Menu
Docs Home
/ / /
Java Reactive Streams Driver
/

Run Commands

On this page

  • Prerequisites
  • Connect to a MongoDB Deployment
  • Run the buildInfo Command

Not all database commands have a specific helper method. However, you can run any MongoDB command by using the MongoDatabase.runCommand() method.

To learn more about MongoDB commands, see Database Commands in the Server manual.

You must set up the following components to run the code examples in this guide:

  • A test.restaurants collection populated with documents from the restaurants.json file in the documentation assets GitHub.

  • The following import statements:

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

Important

This guide uses the Subscriber implementations, which are described in the Quick Start Primer.

First, connect to a MongoDB deployment, then declare and define a MongoDatabase instance.

The following code connects to a standalone MongoDB deployment running on localhost on port 27017. Then, it defines the database variable to refer to the test database:

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

To learn more about connecting to MongoDB deployments, see the Connect to MongoDB tutorial.

To run the buildInfo command, construct a Document object that specifies the command and pass it as a paramter to the runCommand() method.

The following sample code runs the buildInfo command and prints the results:

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

Back

GridFS