diff --git a/source/fundamentals.txt b/source/fundamentals.txt index 20d6cb62..5298dd78 100644 --- a/source/fundamentals.txt +++ b/source/fundamentals.txt @@ -20,6 +20,7 @@ Fundamentals Aggregation Expressions Indexes Transactions + Run a Command Collations Logging Monitoring diff --git a/source/fundamentals/run-command.txt b/source/fundamentals/run-command.txt new file mode 100644 index 00000000..6deba114 --- /dev/null +++ b/source/fundamentals/run-command.txt @@ -0,0 +1,214 @@ +.. _kotlin-run-command: + +============= +Run a Command +============= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +In this guide, you can learn how to run a database command with the +{+driver-short+}. 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. + We recommend using driver methods instead of executing database + commands when possible. + + To perform administrative tasks, use the :mongosh:`MongoDB Shell ` + instead of the {+driver-short+}. Calling the ``db.runCommand()`` + method inside the shell is the preferred method to issue database + commands, as it provides a consistent interface between the shell and + drivers. + +Execute a Command +----------------- + +To run a database command, you must specify the command and any relevant +parameters in a document, then pass this document to a +command execution method. The {+driver-short+} provides the following methods +to run database commands: + +- ``command()``, which returns the command response as a + ``Document`` type. You can use this method with any database command. +- ``runCursorCommand()``, which returns the command response as an iterable + ``RunCommandCursor`` type. You can use this method only if your database command + returns multiple result documents. + +The following code shows how you can use the ``command()`` +method to run the ``hello`` command, which returns information about +the current member's role in the replica set, on a database: + +.. code-block:: javascript + + const result = await myDB.command({ hello: 1 }); + +For a full list of database commands and corresponding parameters, see +the :ref:`Additional Information section `. + +.. _kotlin-command-options: + +Command Options +--------------- + +You can specify optional command behavior for the ``command()`` +and ``runCursorCommand()`` methods. + +The ``command()`` method accepts a ``RunCommandOptions`` object. To learn +more about the ``RunCommandOptions`` type, see the `API documentation <{+api+}/types/RunCommandOptions.html>`__. + +The ``runCursorCommand() method`` accepts a ``RunCursorCommandOptions`` +object. To learn more about the ``RunCursorCommandOptions`` type, see +the `API documentation <{+api+}/types/RunCursorCommandOptions.html>`__. + +Starting in version 6.0 of the {+driver-short+}, you can pass only the +following options to the ``command()`` method: + +- ``comment`` +- ``enableUtf8Validation`` +- ``raw`` +- ``readPreference`` +- ``session`` + +You can set more options in the document that you pass to the ``command()`` method. To +learn more about a command and the options that it accepts, locate the command and follow +the link on the :manual:`Database Commands ` section of the Server +manual. + +The following code shows how to specify a ``grantRolesToUser`` command +that executes with a ``majority`` write concern: + +.. code-block:: javascript + :emphasize-lines: 4 + + const commandDoc = { + grantRolesToUser: "user011", + roles: [ "readWrite" ], + writeConcern: { w: "majority" } + }; + const result = await myDB.command(commandDoc); + +.. note:: Read Preference + + The ``command()`` and ``runCursorCommand()`` methods ignore + the read preference setting you may have set on your ``Db`` object. + By default, these methods use the ``primary`` read preference. + + The following code shows how to specify a read preference and pass it + as an option to the ``command()`` method: + + .. code-block:: javascript + + const commandOptions = { readPreference: "nearest" }; + const result = await myDB.command(commandDoc, commandOptions); + + For more information on read preference options, see :manual:`Read + Preference ` in the Server manual. + +Response +-------- + +Each method returns a ``Document`` object or a cursor that contains +the response from the database after the command has been executed. Each +database command performs a different function, so the response content +can vary across commands. However, every response contains documents +with the following fields: + +.. list-table:: + :header-rows: 1 + :widths: 30 70 + + * - Field + - Description + + * - + - Provides fields specific to the database command. For example, + ``count`` returns the ``n`` field and ``explain`` returns the + ``queryPlanner`` field. + + * - ``ok`` + - Indicates whether the command has succeeded (``1``) + or failed (``0``). + + * - ``operationTime`` + - Indicates the logical time of the operation. MongoDB uses the + logical time to order operations. + To learn more about logical time, see our + :website:`blog post about the Global Logical Clock `. + + * - ``$clusterTime`` + - Provides a document that returns the signed cluster time. Cluster time is a + logical time used for ordering of operations. + + The document contains the following fields: + + - ``clusterTime``, which is the timestamp of the highest known cluster time for the member. + - ``signature``, which is a document that contains the hash of the cluster time and the ID + of the key used to sign the cluster time. + +Example +------- + +The following code shows how you can use the ``runCursorCommand()`` method to +run the ``checkMetadataConsistency`` command on the ``testDB`` database +and iterate through the results: + +.. literalinclude:: /code-snippets/crud/runCommand.js + :language: javascript + :dedent: + :start-after: start-runcommand + :end-before: end-runcommand + +Output +~~~~~~ + +The output contains the contents of the cursor object. The documents +describe any metadata inconsistencies in the database: + +.. code-block:: javascript + + { + type: ..., + description: ..., + details: { + namespace: ..., + info: ... + } + } + { + type: ..., + description: ..., + details: { + namespace: ..., + collectionUUID: ..., + maxKeyObj: ..., + ... + } + } + +.. note:: + + If you store the command response in a cursor, you see only the + command result documents when you access the contents of the cursor. You won't + see the ``ok``, ``operationTime``, and ``$clusterTime`` fields. + +.. _addl-info-runcommand: + +Additional Information +---------------------- + +For more information about the concepts in this guide, see the following documentation: + +- :manual:`db.runCommand() ` +- :manual:`Database Commands ` +- :manual:`hello Command ` +- :manual:`find Command `