Run a Command

For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

Run a Command

Overview

In this guide, you can learn how to run 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.

Important: Prefer Driver Methods to Database Commands

The driver provides wrapper methods for many database commands. We recommend using driver methods instead of executing database commands when possible.

To perform administrative tasks, use the MongoDB Shell instead of the Java driver. Calling the db.runCommand() method inside the shell is the preferred way to issue database commands, as it provides a consistent interface between the shell and drivers.

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.

Run Command Example: Full File

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.](https://www.mongodb.com/docs/drivers/java/sync/current/connection/mongoclient.md#std-label-java-connect-to-mongodb

// Runs a database command by using the Java driver

package org.example;

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

                // Retrieves statistics about the specified database
                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 the [FAQ section](https://www.mongodb.com/docs/drivers/java/sync/current/reference/legacy.md#std-label-java-legacy-api-faq of the Legacy API guide to learn what changes you need to make to this code example.

Additional Information

API Documentation

For more information about the method used to run database commands, see the following API documentation:

  • [runCommand()](https://mongodb.github.io/mongo-java-driver/5.13/apidocs/driver-sync/com/mongodb/client/MongoDatabase.html#runCommand(org.bson.conversions.Bson)

Server Manual Entries