- Reactive Streams
- Tutorials
- Run Commands
Run Commands
Not all commands have a specific helper. However you can run any MongoDB command by using the MongoDatabase’s runCommand()
method.
Prerequisites
The example below requires a
restaurants
collection in thetest
database. To create and populate the collection, follow the directions in github.Include 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 as covered in the Quick Start Primer.
Connect to a MongoDB Deployment
Connect to a MongoDB deployment and declare and define a MongoDatabase
instance.
For example, include the following code to connect to a standalone MongoDB deployment running on localhost on port 27017
and define database
to refer to the test
database:
MongoClient mongoClient = MongoClients.create();
MongoDatabase database = mongoClient.getDatabase("test");
For additional information on connecting to MongoDB, see Connect to MongoDB.
Run buildInfo
and collStats
Commands
To run a command, construct a Document
object that specifies the command and pass it to the runCommand()
method.
The following runs the buildInfo
command and the collStats
command:
database.runCommand(new Document("buildInfo", 1)).subscribe(new PrintDocumentSubscriber());
database.runCommand(new Document("collStats", "restaurants")).subscribe(new PrintDocumentSubscriber());
For a list of available MongoDB commands, see MongoDB commands.