Skip to content
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
1 change: 1 addition & 0 deletions snooty.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ toc_landing_pages = [
"/fundamentals",
"/fundamentals/serialization",
"/upgrade",
"/fundamentals/database-collection"
]

intersphinx = [
Expand Down
3 changes: 3 additions & 0 deletions source/fundamentals/database-collection.txt
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ Databases and Collections
:depth: 2
:class: singlecol

.. toctree::
/fundamentals/databases-collections/run-command

Overview
--------

Expand Down
228 changes: 228 additions & 0 deletions source/fundamentals/databases-collections/run-command.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
.. _csharp-run-command:

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

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: administration, code example

Overview
--------

In this guide, you can learn how to use the {+driver-short+} 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 :mongosh:`MongoDB Shell </>`
instead of the {+driver-short+}. 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
``RunCommand()`` and ``RunCommandAsync()`` methods, which are described in this
guide.

Sample Data
~~~~~~~~~~~

The examples in this guide use the ``sample_restaurants.restaurants`` collection
from the :atlas:`Atlas sample datasets </sample-data>`. To learn how to create a
free MongoDB Atlas cluster and load the sample datasets, see the :ref:`<csharp-quickstart>`.


Execute a Command
-----------------

To run a database command, create a ``BsonDocument`` object that specifies
the command and pass it as a parameter to the ``RunCommand()`` or ``RunCommandAsync()``
method. You can specify the type returned by these methods by specifying the type parameter.
You can use the ``BsonDocument`` type to return the command response, or you can specify your
own strongly typed class to deserialize the command response.

The following example runs the ``hello`` command on a database, which returns information
about the server. Select the :guilabel:`Asynchronous` or :guilabel:`Synchronous`
tab to see the corresponding code.

.. tabs::

.. tab:: Asynchronous
:tabid: run-command-async

.. literalinclude:: /includes/fundamentals/code-examples/databases-collections/RunCommand.cs
:language: csharp
:dedent:
:start-after: start-hello-async
:end-before: end-hello-async

.. tab:: Synchronous
:tabid: distinct-sync

.. literalinclude:: /includes/fundamentals/code-examples/databases-collections/RunCommand.cs
:language: csharp
:dedent:
:start-after: start-hello
:end-before: end-hello

.. tip::

To view a full list of database commands and their corresponding
parameters, see :manual:`Database Commands </reference/command/>` in
the {+mdb-server+} manual.

.. _csharp-command-read-pref:

Set a Read Preference
----------------------

The ``RunCommand()`` method does not inherit the read preference you might
have set on your ``MongoDatabase`` instance. By default, ``RunCommand()``
uses the ``primary`` read preference.

You can set a read preference for the command execution by passing a
``ReadPreference`` instance as a parameter to ``RunCommand()``, as
shown in the following example. Select the :guilabel:`Asynchronous` or :guilabel:`Synchronous`
tab to see the corresponding code.

.. tabs::

.. tab:: Asynchronous
:tabid: run-command-async

.. literalinclude:: /includes/fundamentals/code-examples/databases-collections/RunCommand.cs
:language: csharp
:dedent:
:start-after: start-read-pref-async
:end-before: end-read-pref-async

.. tab:: Synchronous
:tabid: distinct-sync

.. literalinclude:: /includes/fundamentals/code-examples/databases-collections/RunCommand.cs
:language: csharp
:dedent:
:start-after: start-read-pref
:end-before: end-read-pref

.. tip::

To learn more about read preference options, see :manual:`Read
Preference </core/read-preference/>` in the {+mdb-server+} manual.

.. _csharp-command-response:

Response
--------

The raw command response document returned by the ``RunCommand()`` method contains the
following fields:

.. list-table::
:header-rows: 1
:widths: 30 70

* - Field
- Description

* - ``<command result>``
- Fields specific to the database command. For example,
the ``hello`` command returns the ``topologyVersion`` field.

* - ``ok``
- Indicates whether the command has succeeded (``1.0``) or failed (``0.0``). The
driver raises a ``MongoCommandException`` if the ``ok``
value is ``0.0``.

* - ``$clusterTime``
- A document that contains the signed cluster time. Cluster time is a
logical time used for the ordering of operations. This field only
applies to commands run on replica sets or sharded clusters.

* - ``operationTime``
- The logical time of the operation execution. This field only
applies to commands run on replica sets or sharded clusters.

.. tip::

To learn more about logical time, see the Wikipedia entry on
the :wikipedia:`logical clock <w/index.php?title=Logical_clock&oldid=1072010149>`.

Example
~~~~~~~

The following example runs the ``dbStats`` command to retrieve
storage statistics for the ``sample_restaurants`` database, then prints the
command results by using the ``ToJson()`` method on the returned ``BsonDocument`` object.
Select the :guilabel:`Asynchronous` or :guilabel:`Synchronous` tab to see the corresponding
code.

.. tabs::

.. tab:: Asynchronous
:tabid: run-command-async

.. literalinclude:: /includes/fundamentals/code-examples/databases-collections/RunCommand.cs
:language: csharp
:dedent:
:start-after: start-print-command-async
:end-before: end-print-command-async

.. tab:: Synchronous
:tabid: distinct-sync

.. literalinclude:: /includes/fundamentals/code-examples/databases-collections/RunCommand.cs
:language: csharp
:dedent:
:start-after: start-print-command
:end-before: end-print-command

The output of this command includes information about the data stored in
the database, as shown in the result returned by the previous example:

.. code-block:: none
:copyable: false

{ "db" : "sample_restaurants", "collections" : 2, "views" : 0, "objects" :
NumberLong(25438), "avgObjSize" : 548.95172576460413, "dataSize" : NumberLong(13964234),
"storageSize" : NumberLong(8056832), "totalFreeStorageSize" : NumberLong(0),
"numExtents" : NumberLong(0), "indexes" : 2, "indexSize" : NumberLong(1044480),
"indexFreeStorageSize" : NumberLong(0), "fileSize" : NumberLong(0), "nsSizeMB" : 0, "ok" : 1 }


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

For more information about the concepts in this guide, see the following
documentation in the {+mdb-server+} manual:

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

API Documentation
~~~~~~~~~~~~~~~~~

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

- `RunCommand() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoDatabase.RunCommand.html>`_
- `RunCommandAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoDatabase.RunCommandAsync.html>`_
- `ReadPreference <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ReadPreference.html>`_
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using MongoDB.Bson;
using MongoDB.Driver;

public class RunCommand
{
// Replace with your connection string
private const string MongoConnectionString = "<connection string URI>";

public static void Main(string[] args)
{
var mongoClient = new MongoClient(MongoConnectionString);
var database = mongoClient.GetDatabase("sample_restaurants");
var collection = database.GetCollection<BsonDocument>("restaurants");

{
// start-hello
var command = new BsonDocument("hello", 1);
var result = database.RunCommand<BsonDocument>(command);
// end-hello
}

{
// start-read-pref
var command = new BsonDocument("hello", 1);
var result = database.RunCommand<BsonDocument>(command, ReadPreference.Secondary);
// end-read-pref
}

{
// start-print-command
var command = new BsonDocument("dbStats", 1);
var result = database.RunCommand<BsonDocument>(command);
Console.WriteLine(result.ToJson());
// end-print-command
}
}

private static async void RunCommandAsync(IMongoDatabase database)
{
// start-hello-async
var command = new BsonDocument("hello", 1);
var result = await database.RunCommandAsync<BsonDocument>(command);
// end-hello-async
}

private static async void RunCommandReadPrefAsync(IMongoDatabase database)
{
// start-read-pref-async
var command = new BsonDocument("hello", 1);
var result = await database.RunCommandAsync<BsonDocument>(command, ReadPreference.Secondary);
// end-read-pref-async
}

private static async void RunCommandPrintAsync(IMongoDatabase database)
{
// start-print-command-async
var command = new BsonDocument("dbStats", 1);
var result = await database.RunCommandAsync<BsonDocument>(command);
Console.WriteLine(result.ToJson());
// end-print-command-async
}
}
Loading