Run a Database Command
On this page
Overview
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.
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:
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.
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.
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.
Command Example
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.
Type Hints
The Database.command()
method can decode the returned BSON documents to instances
of a specific class. To specify this class, construct a CodecOptions
object and pass
the class name. The class can be one of the following types:
bson.raw_bson.RawBSONDocument
. To learn more about theRawBSONDocument
class, see Work with Raw BSON Data.A subclass of the
collections.abc.Mapping
type, such asOrderedDict
. Depending on the strictness of your type-checking rules, you might also need to specify types for the key and value.A subclass of the
TypedDict
type. To pass aTypedDict
subclass for this parameter, you must also include the class in a type hint for yourCodecOptions
object.
Note
TypedDict in Python 3.7 and Earlier
The TypedDict class
is in the typing
module, which
is available only in Python 3.8 and later. To use the TypedDict
class in
earlier versions of Python, install the
typing_extensions package.
The following example decodes the BSON returned by the ping
command to instances
of the RawBSONDocument
class:
from pymongo import MongoClient from bson.raw_bson import RawBSONDocument from bson import CodecOptions client: MongoClient = MongoClient() options = CodecOptions(RawBSONDocument) result = client.admin.command("ping", codec_options=options)
To decode BSON to a subclass of the TypedDict
class, specify the class name in
the CodecOptions
type hint, as shown in the following example:
from pymongo import MongoClient from bson.raw_bson import RawBSONDocument from bson import CodecOptions from typing import TypedDict class Movie(TypedDict): name: str year: int client: MongoClient = MongoClient() options: CodecOptions[Movie] = CodecOptions(Movie) result = client.admin.command("ping", codec_options=options)
Troubleshooting
Client Type Annotations
If you don't add a type annotation for your MongoClient
object,
your type checker might show an error similar to the following:
from pymongo import MongoClient client = MongoClient() # error: Need type annotation for "client"
The solution is to annotate the MongoClient
object as
client: MongoClient
or client: MongoClient[Dict[str, Any]]
.
Incompatible Type
If you specify MongoClient
as a type hint but don't include data types for
the document, keys, and values, your type checker might show an error similar to
the following:
error: Dict entry 0 has incompatible type "str": "int"; expected "Mapping[str, Any]": "int"
The solution is to add the following type hint to your MongoClient
object:
``client: MongoClient[Dict[str, Any]]``
Additional Information
For more information about the concepts in this guide, see the following documentation in the MongoDB Server manual:
API Documentation
For more information about the command()
and cursor_command()
methods,
see the following PyMongo API documentation: