Skip to content

DOCSP-30358: Run a Command Fundamentals page #702

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jun 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions source/code-snippets/crud/runCommand.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { MongoClient } from "mongodb";

// Replace the uri string with your MongoDB deployment's connection string.
const uri = "<connection string uri>";

const client = new MongoClient(uri);

async function run() {
try {
// start-runcommand
const db = client.db("testDB");
const cursor = await db.runCursorCommand({
checkMetadataConsistency: 1,
});
for await (const doc of cursor) {
console.log(doc);
}
// end-runcommand
} finally {
await client.close();
}
}
run().catch(console.dir);

1 change: 1 addition & 0 deletions source/fundamentals.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Fundamentals
/fundamentals/promises
/fundamentals/aggregation
/fundamentals/transactions
/fundamentals/run-command
/fundamentals/indexes
/fundamentals/collations
/fundamentals/logging
Expand Down
2 changes: 2 additions & 0 deletions source/fundamentals/crud/read-operations/cursor.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
.. _node-access-cursor:

=========================
Access Data From a Cursor
=========================
Expand Down
194 changes: 194 additions & 0 deletions source/fundamentals/run-command.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
.. _node-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.

.. tip::

Use the :mongosh:`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. This 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 command document, then pass the command 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 <addl-info-runcommand>`.

.. note:: Read Preference

``command()`` and ``runCursorCommand()`` do not obey the read
preference you may have set on your ``Db`` object elsewhere in
your code. By default, these methods use the ``primary`` read
preference.

You can set a read preference for command execution by
passing an options object to either method. The ``command()`` method
takes a ``RunCommandOptions`` object, and the ``runCursorCommand()`` method
takes a ``RunCursorCommandOptions`` object.

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 </core/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
Comment on lines +93 to +94
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

S: I'm guessing this means command() returns a Document and runCursorCommand returns a cursor. If so, can we clarify? By saying "Each method...", it sounds like each of the two methods will return one type or the other depending on some unspecified circumstance.

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

* - <command result>
- 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.

.. seealso::

To learn more about logical time, see our :website:`blog post about
the Global Logical Clock </blog/post/transactions-background-part-4-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.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Q: is there a way to see this info when using a cursor?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think so. I can try printing the cursor a few different ways and see what happens, though.

Copy link
Collaborator Author

@rustagir rustagir Jun 5, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

after some testing it seems like you cant, but I will follow up with DBX


.. _addl-info-runcommand:

Additional Information
----------------------

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

- :manual:`db.runCommand() </reference/method/db.runCommand/>`
- :manual:`Database Commands </reference/command/>`
- :manual:`hello Command </reference/command/hello/>`

.. - :manual:`checkMetadataConsistency Command </reference/command/checkMetadataConsistency/>`

To learn how to retrieve data from a cursor, see the
:ref:`node-access-cursor` fundamentals page.
1 change: 1 addition & 0 deletions source/includes/fundamentals-sections.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ Fundamentals section:
- :doc:`Access Return Values </fundamentals/promises>`
- :doc:`Transform your Data </fundamentals/aggregation>`
- :doc:`Create and Manage Transactions </fundamentals/transactions>`
- :doc:`Run a Database Command </fundamentals/run-command>`
- :doc:`Create Indexes to Speed Up Queries </fundamentals/indexes>`
- :doc:`Sort Using Collations </fundamentals/collations>`
- :doc:`Log Events in the Driver </fundamentals/logging>`
Expand Down
4 changes: 2 additions & 2 deletions source/usage-examples/command.txt
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
.. _node-run-command-usageex:

=============
Run a Command
=============

.. default-domain:: mongodb

You can run all raw database operations using the
`db.command() <{+api+}/classes/Db.html#command>`__ method. Call the ``command()`` method with
your command object on an instance of a database for diagnostic and
Expand Down