For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

Run a Database Command

In this guide, you can learn how to use the Ruby driver to run a database command. You can use database commands to perform a variety of administrative and diagnostic tasks, such as fetching server statistics, initializing a replica set, or running an aggregation pipeline.

Important

Prefer Driver Methods to Database Commands

The driver provides wrapper methods for many database commands. If possible, we recommend using these methods instead of executing database commands.

To perform administrative tasks, use the MongoDB Shell instead of the Ruby driver. The shell provides helper methods that might not be available in the driver.

If there are no available helpers in the driver or the shell, you can use the db.runCommand() shell method or the driver's command and cursor_command methods, which are described in this guide.

The examples in this guide use the sample_restaurants database from the Atlas sample datasets. To access this database from your Ruby application, create a Mongo::Client object that connects to an Atlas cluster and assign the following value to your database variable:

database = client.use('sample_restaurants').database

To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.

To run a database command, call the command method on your Mongo::Database instance and pass the name of the operation to run as a parameter.

The following example calls the command method to run the hello command, which returns information about the server:

database.command(hello: 1)

Tip

To view a full list of database commands and their corresponding parameters, see Database Commands in the MongoDB Server manual.

The command method returns a Mongo::Operation::Result that contains the response from the database for the given command.

You can access the fields of the raw command response document by using the following methods:

Method
Description

acknowledged?

Returns true if the server acknowledged the command, and false otherwise.

inspect

Returns a formatted string representation of the command response.

ok?

Returns true if the command succeeded, and false otherwise. If the ok? method returns false, the driver raises a Mongo::Error::OperationFailure .

cluster_time

Returns the cluster time reported in the server response. Cluster time is a logical time used for the ordering of operations. This field only applies to commands run on replica sets or sharded cluster.

operation_time

Returns the logical time of the operation execution.

For a full list of methods available on the Result object, see the API documentation.

Tip

To learn more about logical time, see the Wikipedia entry on the logical clock.

The following example runs the dbStats command to retrieve storage statistics for the sample_restaurants database, then prints the command results by using the inspect method:

puts database.command({dbStats: 1}).first

The output of this command includes information about the data stored in the database, as shown in the following code:

{"db"=>"sample_restaurants", "collections"=>4, "views"=>0, "objects"=>18767, "avgObjSize"=>596.1911866574306,"dataSize"=>11188720, "storageSize"=>7528448, "totalFreeStorageSize"=>0, "numExtents"=>0, "indexes"=>6,"indexSize"=>1519616, "indexFreeStorageSize"=>0, "fileSize"=>0,"nsSizeMB"=>0, "ok"=>1}

Some database commands return their results in a cursor. To run these commands, call the cursor_command method on your Mongo::Database instance. This method returns a Mongo::Cursor object that retrieves additional batches of results from the server as you iterate over it. If the command response doesn't contain a cursor, the driver raises a Mongo::Error::InvalidCursorOperation error.

The following example runs the listCollections command by using the cursor_command method and prints the name and type of each collection in the sample_restaurants database:

cursor = database.cursor_command(listCollections: 1, nameOnly: true)cursor.each do |doc| puts docend

You can pass the following options to the command and cursor_command methods:

Option
Methods
Description

:read

command, cursor_command

The read preference to use for the command. The cursor_command method also uses this read preference for subsequent getMore commands. By default, both methods use the primary read preference.

:session

command, cursor_command

The session to use for the command. If you don't specify a session for the cursor_command method, the driver creates an implicit session that lasts for the lifetime of the cursor.

:timeout_ms

command, cursor_command

The operation timeout, in milliseconds. The value must be a non-negative integer. A value of 0 means no timeout. If you don't set this option, the method inherits the timeout from the database or the client.

:batch_size

cursor_command

The batchSize value to send on getMore commands.

:max_time_ms

cursor_command

The maxTimeMS value to send on getMore commands. To set a time limit on the initial command, include the maxTimeMS field in the command document.

:comment

cursor_command

A comment to attach to getMore commands.

:cursor_type

cursor_command

The cursor type, either :tailable or :tailable_await. This value must match the flags set in the command document.

:timeout_mode

cursor_command

The timeout mode, either :cursor_lifetime or :iteration.

The command and cursor_command methods don't inherit the read preference on your Database instance.

You can set a read preference for the command execution by passing the :read option to the command method, as shown in the following code:

database.command({hello: 1}, read: {mode: :secondary})

Tip

To learn more about read preference options, see Read Preference in the MongoDB Server manual.

For more information about the concepts in this guide, see the following documentation in the MongoDB Server manual:

To learn more about any of the methods or types discussed in this guide, see the following API documentation: