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. Select the Synchronous or
Asynchronous tab to see the corresponding code:
database = client.get_database("my_db") hello = database.command("hello") print(hello)
{ 'topologyVersion': { 'processId': ObjectId('...'), 'counter': 6 }, 'hosts': [...], 'setName': '...', 'setVersion': 114, 'isWritablePrimary': True, 'secondary': False, 'primary': '...', 'tags': {...}, 'me': '...', 'electionId': ..., 'lastWrite': {...}, 'maxBsonObjectSize': 16777216, 'maxMessageSizeBytes': 48000000, 'maxWriteBatchSize': 100000, 'localTime': ..., 'logicalSessionTimeoutMinutes': 30, 'connectionId': ..., 'minWireVersion': 0, 'maxWireVersion': 21, 'readOnly': False, 'ok': 1.0, '$clusterTime': {...}, 'operationTime': ... }
database = client.get_database("my_db") hello = await database.command("hello") print(hello)
{ 'topologyVersion': { 'processId': ObjectId('...'), 'counter': 6 }, 'hosts': [...], 'setName': '...', 'setVersion': 114, 'isWritablePrimary': True, 'secondary': False, 'primary': '...', 'tags': {...}, 'me': '...', 'electionId': ..., 'lastWrite': {...}, 'maxBsonObjectSize': 16777216, 'maxMessageSizeBytes': 48000000, 'maxWriteBatchSize': 100000, 'localTime': ..., 'logicalSessionTimeoutMinutes': 30, 'connectionId': ..., 'minWireVersion': 0, 'maxWireVersion': 21, 'readOnly': False, 'ok': 1.0, '$clusterTime': {...}, 'operationTime': ... }
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. Select the
Synchronous or Asynchronous tab to see the corresponding code:
database = client.get_database("sample_mflix") result = database.cursor_command("find", "movies", filter={"runtime": 11}) print(result.to_list())
{ '_id': ObjectId(...), 'runtime': 11, 'title': 'The Great Train Robbery', ... }, { {'_id': ObjectId(...), 'runtime': 11, 'title': 'Glas', ... }, ...
database = client.get_database("sample_mflix") result = await database.cursor_command("find", "movies", filter={"runtime": 11}) print(result.to_list())
{ '_id': ObjectId(...), 'runtime': 11, 'title': 'The Great Train Robbery', ... }, { {'_id': ObjectId(...), '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. For example:
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. Select the Synchronous or
Asynchronous tab to see the corresponding code:
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}
database = client.get_database("sample_mflix") result = await 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 theRawBSONDocumentclass, see Work with Raw BSON Data.A subclass of the
collections.abc.Mappingtype, 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
TypedDicttype. To pass aTypedDictsubclass for this parameter, you must also include the class in a type hint for yourCodecOptionsobject.
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. Select the Synchronous or
Asynchronous tab to see the corresponding code:
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)
from pymongo import AsyncMongoClient from bson.raw_bson import RawBSONDocument from bson import CodecOptions client: AsyncMongoClient = AsyncMongoClient() options = CodecOptions(RawBSONDocument) result = await 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. Select the
Synchronous or Asynchronous tab to see the corresponding code:
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)
from pymongo import AsyncMongoClient from bson.raw_bson import RawBSONDocument from bson import CodecOptions from typing import TypedDict class Movie(TypedDict): name: str year: int client: AsyncMongoClient = AsyncMongoClient() options: CodecOptions[Movie] = CodecOptions(Movie) result = await 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: