Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversJava Sync

Run a Command

You can run all raw database operations using the MongoDatabase.runCommand() method. A raw database operation is a command you can execute directly on the MongoDB Server CLI. These commands include administrative and diagnostic tasks, such as fetching server stats or initializing a replica set. Call the runCommand() method with a Bson command object on an instance of a MongoDatabase to run your raw database operation.

Tip

Use the MongoDB Shell for administrative tasks instead of the Java driver whenever possible, since these tasks are often quicker and easier to implement with the shell than in a Java application.

The runCommand() method accepts a command in the form of a Bson object. By default, runCommand returns an object of type org.bson.Document containing the output of the database command. You can specify a return type for runCommand() as an optional second parameter.

In the following sample code, we send the dbStats command to request statistics from a specific MongoDB database.

Note

This example connects to an instance of MongoDB using a connection URI. To learn more about connecting to your MongoDB instance, see the connection guide.

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));
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);
}
}
}
}

When you run the preceding command, you should see output similar to the following:

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}

Tip

Legacy API

If you are using the legacy API, see our FAQ page to learn what changes you need to make to this code example.

For additional information on the classes and methods mentioned on this page, see the following resources:

←  Retrieve Distinct Values of a FieldFundamentals →