运行数据库命令
概述
在此指南中,您可以了解如何使用PyMongo运行数据库命令。您可以使用数据库命令执行各种管理性和诊断任务,例如获取服务器统计信息、初始化副本集或运行聚合管道。
重要
优先使用库方法而非数据库命令
库为许多数据库命令提供了包装方法。我们建议在可能的情况下使用这些方法,而不是执行数据库命令。
要执行管理任务,请使用MongoDB Shell 而不是PyMongo。Shell提供了可能在驱动程序中不可用的辅助方法。
如果在库或shell中没有可用的助手,您可以使用db.runCommand()
shell方法或驱动程序的command()
方法,这些方法在本指南中有详细说明。
执行命令
您可以使用command()
方法运行数据库命令。您必须指定命令及其相关参数。如果命令简单,则可以将其作为字符串传递。否则,可以将其作为dict
对象传递。该方法将返回已运行命令的结果。
以下代码演示了如何在Database
上使用command()
方法来运行返回服务器信息的hello
命令
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) }
有关数据库命令及其对应参数的完整列表,请参阅附加信息部分。
命令游标
方法 command()
返回已运行的命令的结果。您还可以使用 cursor_command()
方法,该方法发送 MongoDB 命令并将响应解析为 CommandCursor。可以使用 CommandCursor
来遍历命令结果。
以下示例在 sample_mflix
数据库上使用 cursor_command()
方法。它对 movies
集合上的 find
命令进行运行,以过滤具有 runtime
字段值为 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', ... }, ...
有关命令的响应格式,请参阅 数据库命令。
注意
读取偏好
方法 command()
和 cursor_command()
不遵守您在代码中其他地方设置的数据库实例 Database
的读取偏好。如果提供了一个 ClientSession,则是通过使用 session
参数,并且这个会话处于 事务 中,此时命令的读取偏好将设置为事务的读取偏好。否则,命令的读取偏好默认为 PRIMARY
。
您可以通过使用 read_preference
参数来为命令执行设置读取偏好,如下面的代码所示
from pymongo.read_preferences import Secondary database = client.get_database("my_db") hello = database.command("hello", read_preference=Secondary()) print(hello)
了解有关 read_preferences
模块的更多信息,请参阅API 文档。
要了解更多关于读取偏好选项的信息,请参阅 MongoDB 服务器手册中的读取偏好。
命令示例
以下示例使用 command()
方法运行 dbStats
命令,以检索 sample_mflix
数据库的存储统计信息
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}
此命令的输出包括有关数据库中集合的信息,并描述了跨集合存储的数据量和大小。
更多信息
有关本指南中概念的更多信息,请参阅 MongoDB 服务器手册中的以下文档
API 文档
有关 command()
和 cursor_command()
方法的更多信息,请参阅以下 PyMongo API 文档