Skip to content
New issue

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

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

Already on GitHub? # to your account

DOCSP-45176: Run a command #130

Merged
merged 5 commits into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from 3 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
3 changes: 2 additions & 1 deletion snooty.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ toc_landing_pages = [
"/get-started",
"/connect",
"/write",
"/indexes"
"/indexes",
"/databases-collection"
]

intersphinx = ["https://www.mongodb.com/docs/manual/objects.inv"]
Expand Down
8 changes: 6 additions & 2 deletions source/databases-collection.txt
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ Databases and Collections
.. meta::
:keywords: table, row, organize, storage

.. toctree::
:titlesonly:
:maxdepth: 1

Run a Command </databases-collections/run-command>

Overview
--------

Expand Down Expand Up @@ -122,8 +128,6 @@ To query for only the names of the collections in the database, call the
(i.e. each collection object can be further queried for metadata), while
``database.collection_names`` simply lists the collection names.



Delete a Collection
-------------------

Expand Down
184 changes: 184 additions & 0 deletions source/databases-collections/run-command.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
.. _ruby-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
``command`` method, which is described in this guide.

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

The examples in this guide use the ``sample_restaurants``
database from the :atlas:`Atlas sample datasets </sample-data>`. To access this database
from your {+language+} application, create a ``Mongo::Client`` object that connects to an Atlas cluster
and assign the following value to your ``database`` variable:

.. literalinclude:: /includes/databases-collections/run-command.rb
:language: scala
:dedent:
:start-after: start-db
:end-before: end-db

To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the
:atlas:`Get Started with Atlas </getting-started>` guide.

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

To run a database command, run the ``command`` instance method of a ``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:

.. literalinclude:: /includes/databases-collections/run-command.rb
:language: scala
: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.

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

The ``command`` method does not inherit the read preference you might
have set on your ``Database`` instance. By default, ``command``
uses the ``primary`` read preference.

You can set a read preference for the command execution by passing a
``ReadPreference`` instance as a parameter to ``command``, as
shown in the following code:
Copy link
Contributor

Choose a reason for hiding this comment

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

The example given after this paragraph does not use a ReadPreference instance, instead passing a hash of read preference options. Maybe the paragraph could be adjusted something like:

Suggested change
You can set a read preference for the command execution by passing a
``ReadPreference`` instance as a parameter to ``command``, as
shown in the following code:
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:


.. literalinclude:: /includes/databases-collections/run-command.rb
:language: scala
:dedent:
:start-after: start-readpref
:end-before: end-readpref

.. tip::

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

Response
--------

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:

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

* - 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 <{+api-root+}/Mongo/Operation/Result.html>`__.

.. 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 ``inspect`` method:

.. literalinclude:: /includes/databases-collections/run-command.rb
:language: ruby
: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 following code:

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

{"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}

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:

- `command <{+api-root+}/Mongo/Database.html#command-instance_method>`_
25 changes: 25 additions & 0 deletions source/includes/databases-collections/run-command.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'mongo'
end

uri = "<connection string>"

Mongo::Client.new(uri) do |client|
# start-db
database = client.use('sample_restaurants')
# end-db

# start-hello
client.database.command(hello: 1)
# end-hello

# start-readpref
client.database.command({hello: 1}, read: {mode: :secondary})
# end-readpref

# start-print-command
puts client.database.command({dbStats: 1}).first
# end-print-command
end
2 changes: 1 addition & 1 deletion source/write/delete.txt
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ Sample Data

The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants``
database from the :atlas:`Atlas sample datasets </sample-data>`. To access this collection
from your {+language+} application, create a ``MongoClient`` that connects to an Atlas cluster
from your {+language+} application, create a ``Mongo::Client`` object that connects to an Atlas cluster
and assign the following values to your ``database`` and ``collection`` variables:

.. literalinclude:: /includes/write/delete.rb
Expand Down
2 changes: 1 addition & 1 deletion source/write/replace.txt
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ Sample Data

The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants``
database from the :atlas:`Atlas sample datasets </sample-data>`. To access this collection
from your {+language+} application, create a ``MongoClient`` object that connects to an Atlas cluster
from your {+language+} application, create a ``Mongo::Client`` object that connects to an Atlas cluster
and assign the following values to your ``database`` and ``collection`` variables:

.. literalinclude:: /includes/write/replace.rb
Expand Down
Loading