Skip to content

DOCSP-37565: Run Command #118

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 6 commits into from
Nov 5, 2024
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
41 changes: 41 additions & 0 deletions source/includes/run-command.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# start-hello

database = client.get_database("my_db")

hello = database.command("hello")

print(hello)

# end-hello

# start-readpref

from pymongo.read_preferences import Secondary

database = client.get_database("my_db")

hello = database.command("hello", read_preference=Secondary())

print(hello)

# end-readpref

# start-cursor-command

database = client.get_database("sample_mflix")

result = database.cursor_command("find", "movies", filter={"runtime": 11})

print(result.to_list())

# end-cursor-command

# start-runcommand

database = client.get_database("sample_mflix")

result = database.command("dbStats")

print(result)

# end-runcommand
6 changes: 6 additions & 0 deletions source/index.txt
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ MongoDB {+driver-short+} Documentation
/databases-collections
/write-operations
/read
/run-command
/indexes
/aggregation
/security
Expand Down Expand Up @@ -68,6 +69,11 @@ Read Data from MongoDB

Learn how you can retrieve data from MongoDB in the :ref:`pymongo-read` section.

Run a Database Command
----------------------

Learn how to run a database command in the :ref:`pymongo-run-command` section.

Optimize Queries with Indexes
-----------------------------

Expand Down
247 changes: 247 additions & 0 deletions source/run-command.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,247 @@
.. _pymongo-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 {+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 Library Methods to Database Commands

The library provides wrapper methods for many database commands.
We recommend using these methods instead of executing database
commands when possible.

To perform administrative tasks, use the :mongosh:`MongoDB Shell </>`
instead of {+driver-short+}. The shell provides helper methods
that might not be available in the driver.

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

.. _pymongo-execute-command:

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

You can use the ``command()`` method to run a database command. You must specify
the command and any relevant arguments. If the command is simple, these can be
passed as strings. Otherwise, they can be passed as a ``dict`` object.
The method will return the result of the command that was run.

The following code shows how you can use the ``command()``
method on a ``Database`` to run the ``hello``
command, which returns information about the server:

.. io-code-block::
:copyable: true

.. input:: /includes/run-command.py
:language: python
:start-after: start-hello
:end-before: end-hello

.. output::
:language: json
:visible: false

{
'topologyVersion': {
'processId': ObjectId('6724d211d6b98fa1931e8616'),
'counter': 6
},
'hosts': ['cluster0-shard-00-00.fxoii.mongodb.net:27017',
'cluster0-shard-00-01.fxoii.mongodb.net:27017',
'cluster0-shard-00-02.fxoii.mongodb.net:27017'],
'setName': 'atlas-13l6uw-shard-0',
'setVersion': 114,
'isWritablePrimary': True,
'secondary': False,
'primary': 'cluster0-shard-00-02.fxoii.mongodb.net:27017',
'tags': {
'workloadType': 'OPERATIONAL',
'diskState': 'READY',
'region': 'US_EAST_1',
'provider': 'AWS',
'nodeType': 'ELECTABLE',
'availabilityZone': 'use1-az5'
},
'me': 'cluster0-shard-00-02.fxoii.mongodb.net:27017',
'electionId': ObjectId('7fffffff00000000000000e3'),
'lastWrite': {
'opTime': {
'ts': Timestamp(1730486145, 22),
't': 227
},
'lastWriteDate': datetime.datetime(2024, 11, 1, 18, 35, 45),
'majorityOpTime': {
'ts': Timestamp(1730486145, 22),
't': 227
},
'majorityWriteDate': datetime.datetime(2024, 11, 1, 18, 35, 45)
},
'maxBsonObjectSize': 16777216,
'maxMessageSizeBytes': 48000000,
'maxWriteBatchSize': 100000,
'localTime': datetime.datetime(2024, 11, 1, 18, 35, 45, 309000),
'logicalSessionTimeoutMinutes': 30,
'connectionId': 23889,
'minWireVersion': 0,
'maxWireVersion': 21,
'readOnly': False,
'ok': 1.0,
'$clusterTime': {
'clusterTime': Timestamp(1730486145, 22),
'signature': {
'hash': b"\x1a\xf7{>q%F\xc2\x89\x15\x13W29\x91\xaae'~\xe4",
'keyId': 7379292132843978793
}
},
'operationTime': Timestamp(1730486145, 22)
}

For a full list of database commands and corresponding
parameters, see the :ref:`Additional Information section
<pymongo-addtl-info-runcommand>`.

.. _pymongo-command-response:

Command Cursor
--------------

The ``command()`` method returns the result of the command that was run.
You can also use the ``cursor_command()`` method, which issues a MongoDB
command and parses the response as a `CommandCursor <{+api-root+}pymongo/command_cursor.html#pymongo.command_cursor.CommandCursor>`__.
The ``CommandCursor`` can be used to iterate over command results.

The following example uses the ``cursor_command()`` method on the ``sample_mflix``
database. It runs the ``find`` command on the ``movies`` database to filter by
documents in which the ``runtime`` field has a value of ``11``.

.. io-code-block::
:copyable: true

.. input:: /includes/run-command.py
:language: python
:dedent:
:start-after: start-cursor-command
:end-before: end-cursor-command

.. output::
:language: json
:visible: false

{
'_id': ObjectId('573a1390f29313caabcd42e8'),
'runtime': 11,
'title': 'The Great Train Robbery',
...
},
{
{'_id': ObjectId('573a1394f29313caabce0f10'),
'runtime': 11,
'title': 'Glas',
...
},
...

To learn about the response format of the command, see :manual:`Database Commands </reference/command/>`.

.. note:: Read Preference

The ``command()`` and ``cursor_command()`` methods do not obey the read preference you might
have set on your ``Database`` instance elsewhere in your code. If a
`ClientSession <{+api-root+}pymongo/client_session.html#pymongo.client_session.ClientSession>`__ is
provided by using the ``session`` parameter, and this session is in a
`transaction <{+api-root+}pymongo/client_session.html#transactions>`__, the command's
read preference will be set to the transaction's read preference. Otherwise,
the command's read preference defaults to ``PRIMARY``.

You can set a read preference for command execution by using the ``read_preference``
parameter, as shown in the following code:

.. literalinclude:: /includes/run-command.py
:language: python
:dedent:
:start-after: start-readpref
:end-before: end-readpref

Learn more about the ``read_preferences`` module in the `API documentation
<{+api-root+}pymongo/read_preferences.html#module-pymongo.read_preferences>`__.

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

.. _pymongo-command-example:

Command Example
---------------

The following example uses the ``command()`` method to run
the ``dbStats`` command to retrieve storage statistics for the
``sample_mflix`` database:

.. io-code-block::
:copyable: true

.. input:: /includes/run-command.py
:language: python
:start-after: start-runcommand
:end-before: end-runcommand

.. output::
:language: none
:visible: false

{'db': 'sample_mflix', 'collections': 9, 'views': 1, 'objects': 67662,
'avgObjSize': 1796.788182436227, 'dataSize': 121574282, 'storageSize': 97779712,
'totalFreeStorageSize': 0, 'numExtents': 0, 'indexes': 13, 'indexSize': 19423232,
'indexFreeStorageSize': 0, 'fileSize': 0, 'nsSizeMB': 0, 'ok': 1}

The output of this command includes information about the collections in
the database, and describes the amount and size of data stored across
collections.

.. _pymongo-addtl-info-runcommand:

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:`find Command </reference/command/find>`
- :manual:`dbStats Command </reference/command/dbStats/>`

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

For more information about the ``command()`` and ``cursor_command()`` methods,
see the following {+driver-short+} API documentation:

- `command() <{+api-root+}pymongo/database.html#pymongo.database.Database.command>`__
- `cursor_command() <{+api-root+}pymongo/database.html#pymongo.database.Database.cursor_command>`__
Loading