From de73ea6b59dd62353ca726a345c9bb82555eb1fc Mon Sep 17 00:00:00 2001 From: Maya Raman Date: Fri, 1 Nov 2024 14:25:45 -0400 Subject: [PATCH 1/6] initial commit --- source/includes/run-command.py | 41 +++++++++ source/index.txt | 6 ++ source/run-command.txt | 164 +++++++++++++++++++++++++++++++++ 3 files changed, 211 insertions(+) create mode 100644 source/includes/run-command.py create mode 100644 source/run-command.txt diff --git a/source/includes/run-command.py b/source/includes/run-command.py new file mode 100644 index 00000000..24403c7f --- /dev/null +++ b/source/includes/run-command.py @@ -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", "movies") + +print(result) + +# end-runcommand \ No newline at end of file diff --git a/source/index.txt b/source/index.txt index fb4565c4..8b142745 100644 --- a/source/index.txt +++ b/source/index.txt @@ -17,6 +17,7 @@ MongoDB {+driver-short+} Documentation /databases-collections /write-operations /read + /run-command /indexes /aggregation /security @@ -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 ----------------------------- diff --git a/source/run-command.txt b/source/run-command.txt new file mode 100644 index 00000000..96f78940 --- /dev/null +++ b/source/run-command.txt @@ -0,0 +1,164 @@ +.. _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 +----------------- + +To run a database command, you must specify the command and any relevant +parameters in a command document, then pass the command document to the +``command()`` method. + +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: + +.. literalinclude:: /includes/run-command.py + :language: python + :start-after: start-hello + :end-before: end-hello + +To find a link to a full list of database commands and corresponding +parameters, see the :ref:`Additional Information section +`. + +.. _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+}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``. + +.. literalinclude:: /includes/run-command.py + :language: python + :dedent: + :start-after: start-cursor-command + :end-before: end-cursor-command + +Before you run a command, learn about the response format of the command so that +you can handle the ``CommandCursor`` accordingly. + +.. 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 + `Client Session <{+api-root+}bson/objectid.html#bson.objectid.ObjectId>`__ is + provided by using the ``session`` parameter, and this session is in a + `transaction <{+api-root+}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+}read_preferences.html#module-pymongo.read_preferences>`__. + + To learn more about read preference options, see :manual:`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() ` +- :manual:`Database Commands ` +- :manual:`hello Command ` +- :manual:`find Command ` +- :manual:`dbStats Command ` + +API Documentation +~~~~~~~~~~~~~~~~~ + +For more information about the ``command()`` and ``cursor_command()`` methods, +see the following {+driver-short+} API documentation: + +- `command() <{+api-root+}database.html#pymongo.database.Database.command>`__ +- `cursor_command() <{+api-root+}database.html#pymongo.database.Database.cursor_command>`__ \ No newline at end of file From 6588992965bc8c0af860e4edc9c5c85636bc03f2 Mon Sep 17 00:00:00 2001 From: Maya Raman Date: Fri, 1 Nov 2024 14:55:04 -0400 Subject: [PATCH 2/6] fixes in code and opening --- source/includes/run-command.py | 2 +- source/run-command.txt | 107 +++++++++++++++++++++++++++++---- 2 files changed, 96 insertions(+), 13 deletions(-) diff --git a/source/includes/run-command.py b/source/includes/run-command.py index 24403c7f..132f5116 100644 --- a/source/includes/run-command.py +++ b/source/includes/run-command.py @@ -34,7 +34,7 @@ database = client.get_database("sample_mflix") -result = database.command("dbStats", "movies") +result = database.command("dbStats") print(result) diff --git a/source/run-command.txt b/source/run-command.txt index 96f78940..a1518e1c 100644 --- a/source/run-command.txt +++ b/source/run-command.txt @@ -45,18 +45,80 @@ statistics, initializing a replica set, or running an aggregation pipeline. 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 the -``command()`` method. +You can use the ``command()`` method to run a database command. You must specify +the command and any relevant parameters. These can be passed as strings or as +a ``dict``. 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: -.. literalinclude:: /includes/run-command.py - :language: python - :start-after: start-hello - :end-before: end-hello +.. 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) + } To find a link to a full list of database commands and corresponding parameters, see the :ref:`Additional Information section @@ -76,11 +138,32 @@ 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``. -.. literalinclude:: /includes/run-command.py - :language: python - :dedent: - :start-after: start-cursor-command - :end-before: end-cursor-command +.. 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', + ... + }, + ... Before you run a command, learn about the response format of the command so that you can handle the ``CommandCursor`` accordingly. From 472b79df0ffa96487e428dc4cb18603d74ab1238 Mon Sep 17 00:00:00 2001 From: Maya Raman Date: Fri, 1 Nov 2024 15:26:42 -0400 Subject: [PATCH 3/6] links --- source/run-command.txt | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/source/run-command.txt b/source/run-command.txt index a1518e1c..d219f575 100644 --- a/source/run-command.txt +++ b/source/run-command.txt @@ -55,7 +55,7 @@ command, which returns information about the server: .. io-code-block:: :copyable: true - + .. input:: /includes/run-command.py :language: python :start-after: start-hello @@ -131,7 +131,7 @@ 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+}command_cursor.html#pymongo.command_cursor.CommandCursor>`__. +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`` @@ -172,9 +172,9 @@ you can handle the ``CommandCursor`` accordingly. 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 - `Client Session <{+api-root+}bson/objectid.html#bson.objectid.ObjectId>`__ is + `Client Session <{+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+}client_session.html#transactions>`__, the command's + `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``. @@ -188,7 +188,7 @@ you can handle the ``CommandCursor`` accordingly. :end-before: end-readpref Learn more about the ``read_preferences`` module in the `API documentation - <{+api-root+}read_preferences.html#module-pymongo.read_preferences>`__. + <{+api-root+}pymongo/read_preferences.html#module-pymongo.read_preferences>`__. To learn more about read preference options, see :manual:`Read Preference ` in the {+mdb-server+} manual. @@ -243,5 +243,5 @@ API Documentation For more information about the ``command()`` and ``cursor_command()`` methods, see the following {+driver-short+} API documentation: -- `command() <{+api-root+}database.html#pymongo.database.Database.command>`__ -- `cursor_command() <{+api-root+}database.html#pymongo.database.Database.cursor_command>`__ \ No newline at end of file +- `command() <{+api-root+}pymongo/database.html#pymongo.database.Database.command>`__ +- `cursor_command() <{+api-root+}pymongo/database.html#pymongo.database.Database.cursor_command>`__ \ No newline at end of file From e0cb4ab971f9272a35b900175d166c6d96d19501 Mon Sep 17 00:00:00 2001 From: Maya Raman Date: Fri, 1 Nov 2024 15:28:37 -0400 Subject: [PATCH 4/6] parameters --- source/run-command.txt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/source/run-command.txt b/source/run-command.txt index d219f575..24a2e5dd 100644 --- a/source/run-command.txt +++ b/source/run-command.txt @@ -46,8 +46,9 @@ Execute a Command ----------------- You can use the ``command()`` method to run a database command. You must specify -the command and any relevant parameters. These can be passed as strings or as -a ``dict``. The method will return the result of the command that was run. +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``. +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`` From 5da5dec5e23d051195bf33bc4f6ca759148b4194 Mon Sep 17 00:00:00 2001 From: Maya Raman Date: Fri, 1 Nov 2024 15:31:22 -0400 Subject: [PATCH 5/6] client session --- source/run-command.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/run-command.txt b/source/run-command.txt index 24a2e5dd..025ad534 100644 --- a/source/run-command.txt +++ b/source/run-command.txt @@ -173,7 +173,7 @@ you can handle the ``CommandCursor`` accordingly. 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 - `Client Session <{+api-root+}pymongo/client_session.html#pymongo.client_session.ClientSession>`__ is + `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, From 44f9cc35999e8f2dcedcab812bb29444b9a3df10 Mon Sep 17 00:00:00 2001 From: Maya Raman Date: Mon, 4 Nov 2024 17:04:15 -0500 Subject: [PATCH 6/6] feedback --- source/run-command.txt | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/source/run-command.txt b/source/run-command.txt index 025ad534..f16bc370 100644 --- a/source/run-command.txt +++ b/source/run-command.txt @@ -47,7 +47,7 @@ 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``. +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()`` @@ -121,7 +121,7 @@ command, which returns information about the server: 'operationTime': Timestamp(1730486145, 22) } -To find a link to a full list of database commands and corresponding +For a full list of database commands and corresponding parameters, see the :ref:`Additional Information section `. @@ -137,7 +137,7 @@ 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``. +documents in which the ``runtime`` field has a value of ``11``. .. io-code-block:: :copyable: true @@ -166,8 +166,7 @@ documents in which the ``runtime``field has a value of ``11``. }, ... -Before you run a command, learn about the response format of the command so that -you can handle the ``CommandCursor`` accordingly. +To learn about the response format of the command, see :manual:`Database Commands `. .. note:: Read Preference