|
| 1 | +.. _pymongo-run-command: |
| 2 | + |
| 3 | +====================== |
| 4 | +Run a Database Command |
| 5 | +====================== |
| 6 | + |
| 7 | +.. contents:: On this page |
| 8 | + :local: |
| 9 | + :backlinks: none |
| 10 | + :depth: 2 |
| 11 | + :class: singlecol |
| 12 | + |
| 13 | +.. facet:: |
| 14 | + :name: genre |
| 15 | + :values: reference |
| 16 | + |
| 17 | +.. meta:: |
| 18 | + :keywords: administration, code example |
| 19 | + |
| 20 | +Overview |
| 21 | +-------- |
| 22 | + |
| 23 | +In this guide, you can learn how to use {+driver-short+} |
| 24 | +to run a database command. You can use database commands to perform a |
| 25 | +variety of administrative and diagnostic tasks, such as fetching server |
| 26 | +statistics, initializing a replica set, or running an aggregation pipeline. |
| 27 | + |
| 28 | +.. important:: Prefer Library Methods to Database Commands |
| 29 | + |
| 30 | + The library provides wrapper methods for many database commands. |
| 31 | + We recommend using these methods instead of executing database |
| 32 | + commands when possible. |
| 33 | + |
| 34 | + To perform administrative tasks, use the :mongosh:`MongoDB Shell </>` |
| 35 | + instead of {+driver-short+}. The shell provides helper methods |
| 36 | + that might not be available in the driver. |
| 37 | + |
| 38 | + If there are no available helpers in the library or the shell, you |
| 39 | + can use the ``db.runCommand()`` shell method or the driver's |
| 40 | + ``command()`` method, which is described in this |
| 41 | + guide. |
| 42 | + |
| 43 | +.. _pymongo-execute-command: |
| 44 | + |
| 45 | +Execute a Command |
| 46 | +----------------- |
| 47 | + |
| 48 | +You can use the ``command()`` method to run a database command. You must specify |
| 49 | +the command and any relevant arguments. If the command is simple, these can be |
| 50 | +passed as strings. Otherwise, they can be passed as a ``dict`` object. |
| 51 | +The method will return the result of the command that was run. |
| 52 | + |
| 53 | +The following code shows how you can use the ``command()`` |
| 54 | +method on a ``Database`` to run the ``hello`` |
| 55 | +command, which returns information about the server: |
| 56 | + |
| 57 | +.. io-code-block:: |
| 58 | + :copyable: true |
| 59 | + |
| 60 | + .. input:: /includes/run-command.py |
| 61 | + :language: python |
| 62 | + :start-after: start-hello |
| 63 | + :end-before: end-hello |
| 64 | + |
| 65 | + .. output:: |
| 66 | + :language: json |
| 67 | + :visible: false |
| 68 | + |
| 69 | + { |
| 70 | + 'topologyVersion': { |
| 71 | + 'processId': ObjectId('6724d211d6b98fa1931e8616'), |
| 72 | + 'counter': 6 |
| 73 | + }, |
| 74 | + 'hosts': ['cluster0-shard-00-00.fxoii.mongodb.net:27017', |
| 75 | + 'cluster0-shard-00-01.fxoii.mongodb.net:27017', |
| 76 | + 'cluster0-shard-00-02.fxoii.mongodb.net:27017'], |
| 77 | + 'setName': 'atlas-13l6uw-shard-0', |
| 78 | + 'setVersion': 114, |
| 79 | + 'isWritablePrimary': True, |
| 80 | + 'secondary': False, |
| 81 | + 'primary': 'cluster0-shard-00-02.fxoii.mongodb.net:27017', |
| 82 | + 'tags': { |
| 83 | + 'workloadType': 'OPERATIONAL', |
| 84 | + 'diskState': 'READY', |
| 85 | + 'region': 'US_EAST_1', |
| 86 | + 'provider': 'AWS', |
| 87 | + 'nodeType': 'ELECTABLE', |
| 88 | + 'availabilityZone': 'use1-az5' |
| 89 | + }, |
| 90 | + 'me': 'cluster0-shard-00-02.fxoii.mongodb.net:27017', |
| 91 | + 'electionId': ObjectId('7fffffff00000000000000e3'), |
| 92 | + 'lastWrite': { |
| 93 | + 'opTime': { |
| 94 | + 'ts': Timestamp(1730486145, 22), |
| 95 | + 't': 227 |
| 96 | + }, |
| 97 | + 'lastWriteDate': datetime.datetime(2024, 11, 1, 18, 35, 45), |
| 98 | + 'majorityOpTime': { |
| 99 | + 'ts': Timestamp(1730486145, 22), |
| 100 | + 't': 227 |
| 101 | + }, |
| 102 | + 'majorityWriteDate': datetime.datetime(2024, 11, 1, 18, 35, 45) |
| 103 | + }, |
| 104 | + 'maxBsonObjectSize': 16777216, |
| 105 | + 'maxMessageSizeBytes': 48000000, |
| 106 | + 'maxWriteBatchSize': 100000, |
| 107 | + 'localTime': datetime.datetime(2024, 11, 1, 18, 35, 45, 309000), |
| 108 | + 'logicalSessionTimeoutMinutes': 30, |
| 109 | + 'connectionId': 23889, |
| 110 | + 'minWireVersion': 0, |
| 111 | + 'maxWireVersion': 21, |
| 112 | + 'readOnly': False, |
| 113 | + 'ok': 1.0, |
| 114 | + '$clusterTime': { |
| 115 | + 'clusterTime': Timestamp(1730486145, 22), |
| 116 | + 'signature': { |
| 117 | + 'hash': b"\x1a\xf7{>q%F\xc2\x89\x15\x13W29\x91\xaae'~\xe4", |
| 118 | + 'keyId': 7379292132843978793 |
| 119 | + } |
| 120 | + }, |
| 121 | + 'operationTime': Timestamp(1730486145, 22) |
| 122 | + } |
| 123 | + |
| 124 | +For a full list of database commands and corresponding |
| 125 | +parameters, see the :ref:`Additional Information section |
| 126 | +<pymongo-addtl-info-runcommand>`. |
| 127 | + |
| 128 | +.. _pymongo-command-response: |
| 129 | + |
| 130 | +Command Cursor |
| 131 | +-------------- |
| 132 | + |
| 133 | +The ``command()`` method returns the result of the command that was run. |
| 134 | +You can also use the ``cursor_command()`` method, which issues a MongoDB |
| 135 | +command and parses the response as a `CommandCursor <{+api-root+}pymongo/command_cursor.html#pymongo.command_cursor.CommandCursor>`__. |
| 136 | +The ``CommandCursor`` can be used to iterate over command results. |
| 137 | + |
| 138 | +The following example uses the ``cursor_command()`` method on the ``sample_mflix`` |
| 139 | +database. It runs the ``find`` command on the ``movies`` database to filter by |
| 140 | +documents in which the ``runtime`` field has a value of ``11``. |
| 141 | + |
| 142 | +.. io-code-block:: |
| 143 | + :copyable: true |
| 144 | + |
| 145 | + .. input:: /includes/run-command.py |
| 146 | + :language: python |
| 147 | + :dedent: |
| 148 | + :start-after: start-cursor-command |
| 149 | + :end-before: end-cursor-command |
| 150 | + |
| 151 | + .. output:: |
| 152 | + :language: json |
| 153 | + :visible: false |
| 154 | + |
| 155 | + { |
| 156 | + '_id': ObjectId('573a1390f29313caabcd42e8'), |
| 157 | + 'runtime': 11, |
| 158 | + 'title': 'The Great Train Robbery', |
| 159 | + ... |
| 160 | + }, |
| 161 | + { |
| 162 | + {'_id': ObjectId('573a1394f29313caabce0f10'), |
| 163 | + 'runtime': 11, |
| 164 | + 'title': 'Glas', |
| 165 | + ... |
| 166 | + }, |
| 167 | + ... |
| 168 | + |
| 169 | +To learn about the response format of the command, see :manual:`Database Commands </reference/command/>`. |
| 170 | + |
| 171 | +.. note:: Read Preference |
| 172 | + |
| 173 | + The ``command()`` and ``cursor_command()`` methods do not obey the read preference you might |
| 174 | + have set on your ``Database`` instance elsewhere in your code. If a |
| 175 | + `ClientSession <{+api-root+}pymongo/client_session.html#pymongo.client_session.ClientSession>`__ is |
| 176 | + provided by using the ``session`` parameter, and this session is in a |
| 177 | + `transaction <{+api-root+}pymongo/client_session.html#transactions>`__, the command's |
| 178 | + read preference will be set to the transaction's read preference. Otherwise, |
| 179 | + the command's read preference defaults to ``PRIMARY``. |
| 180 | + |
| 181 | + You can set a read preference for command execution by using the ``read_preference`` |
| 182 | + parameter, as shown in the following code: |
| 183 | + |
| 184 | + .. literalinclude:: /includes/run-command.py |
| 185 | + :language: python |
| 186 | + :dedent: |
| 187 | + :start-after: start-readpref |
| 188 | + :end-before: end-readpref |
| 189 | + |
| 190 | + Learn more about the ``read_preferences`` module in the `API documentation |
| 191 | + <{+api-root+}pymongo/read_preferences.html#module-pymongo.read_preferences>`__. |
| 192 | + |
| 193 | + To learn more about read preference options, see :manual:`Read |
| 194 | + Preference </core/read-preference/>` in the {+mdb-server+} manual. |
| 195 | + |
| 196 | +.. _pymongo-command-example: |
| 197 | + |
| 198 | +Command Example |
| 199 | +--------------- |
| 200 | + |
| 201 | +The following example uses the ``command()`` method to run |
| 202 | +the ``dbStats`` command to retrieve storage statistics for the |
| 203 | +``sample_mflix`` database: |
| 204 | + |
| 205 | +.. io-code-block:: |
| 206 | + :copyable: true |
| 207 | + |
| 208 | + .. input:: /includes/run-command.py |
| 209 | + :language: python |
| 210 | + :start-after: start-runcommand |
| 211 | + :end-before: end-runcommand |
| 212 | + |
| 213 | + .. output:: |
| 214 | + :language: none |
| 215 | + :visible: false |
| 216 | + |
| 217 | + {'db': 'sample_mflix', 'collections': 9, 'views': 1, 'objects': 67662, |
| 218 | + 'avgObjSize': 1796.788182436227, 'dataSize': 121574282, 'storageSize': 97779712, |
| 219 | + 'totalFreeStorageSize': 0, 'numExtents': 0, 'indexes': 13, 'indexSize': 19423232, |
| 220 | + 'indexFreeStorageSize': 0, 'fileSize': 0, 'nsSizeMB': 0, 'ok': 1} |
| 221 | + |
| 222 | +The output of this command includes information about the collections in |
| 223 | +the database, and describes the amount and size of data stored across |
| 224 | +collections. |
| 225 | + |
| 226 | +.. _pymongo-addtl-info-runcommand: |
| 227 | + |
| 228 | +Additional Information |
| 229 | +---------------------- |
| 230 | + |
| 231 | +For more information about the concepts in this guide, see the following |
| 232 | +documentation in the {+mdb-server+} manual: |
| 233 | + |
| 234 | +- :manual:`db.runCommand() </reference/method/db.runCommand/>` |
| 235 | +- :manual:`Database Commands </reference/command/>` |
| 236 | +- :manual:`hello Command </reference/command/hello/>` |
| 237 | +- :manual:`find Command </reference/command/find>` |
| 238 | +- :manual:`dbStats Command </reference/command/dbStats/>` |
| 239 | + |
| 240 | +API Documentation |
| 241 | +~~~~~~~~~~~~~~~~~ |
| 242 | + |
| 243 | +For more information about the ``command()`` and ``cursor_command()`` methods, |
| 244 | +see the following {+driver-short+} API documentation: |
| 245 | + |
| 246 | +- `command() <{+api-root+}pymongo/database.html#pymongo.database.Database.command>`__ |
| 247 | +- `cursor_command() <{+api-root+}pymongo/database.html#pymongo.database.Database.cursor_command>`__ |
0 commit comments