Docs Menu
Docs Home
/ / /
PyMongo

Run a Database Command

On this page

  • Overview
  • Execute a Command
  • Command Cursor
  • Command Example
  • Additional Information
  • API Documentation

In this guide, you can learn how to use PyMongo 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 MongoDB Shell instead of PyMongo. 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.

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:

database = client.get_database("my_db")
hello = database.command("hello")
print(hello)
{
'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 Additional Information section.

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. 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 collection to filter by documents in which the runtime field has a value of 11.

database = client.get_database("sample_mflix")
result = database.cursor_command("find", "movies", filter={"runtime": 11})
print(result.to_list())
{
'_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 Database Commands.

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 is provided by using the session parameter, and this session is in a transaction, 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:

from pymongo.read_preferences import Secondary
database = client.get_database("my_db")
hello = database.command("hello", read_preference=Secondary())
print(hello)

Learn more about the read_preferences module in the API documentation.

To learn more about read preference options, see Read Preference in the MongoDB Server manual.

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

database = client.get_database("sample_mflix")
result = database.command("dbStats")
print(result)
{'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.

For more information about the concepts in this guide, see the following documentation in the MongoDB Server manual:

For more information about the command() and cursor_command() methods, see the following PyMongo API documentation:

Back

Monitor Data Changes