Overview
本页包含的代码示例展示了如何使用各种设置将 Python 应用程序连接到 MongoDB。
提示
要了解有关此页面上的连接选项的更多信息,请参阅每个部分中提供的链接。
要使用此页面中的连接示例,请将代码示例复制到示例应用程序或您自己的应用程序中。 请务必将代码示例中的所有占位符(例如<hostname> )替换为 MongoDB 部署的相关值。
示例应用程序
您可以使用以下示例应用程序来测试本页上的代码示例。 要使用示例应用程序,请执行以下步骤:
确保已安装 PyMongo。
复制以下代码并将其粘贴到新的
.py文件中。从此页面复制代码示例,并将其粘贴到文件中的指定行。
选择 Synchronous 或 Asynchronous标签页,查看相应的代码:
from pymongo import MongoClient
try: # start example code here
# end example code here
client.admin.command("ping") print("Connected successfully")
# other application code
client.close()
except Exception as e: raise Exception( "The following error occurred: ", e)import asynciofrom pymongo import AsyncMongoClient
async def main(): try: # start example code here
# end example code here
await client.admin.command("ping") print("Connected successfully")
# other application code
await client.close()
except Exception as e: raise Exception( "The following error occurred: ", e)
asyncio.run(main())连接
以下部分介绍如何连接到不同的目标,例如MongoDB的本地实例或Atlas上的云托管实例。
本地部署
以下代码显示了如何连接连接字符串以连接到本地MongoDB 部署。 选择 Synchronous 或 Asynchronous标签页,查看相应的代码:
uri = "mongodb://localhost:27017/"client = MongoClient(uri)uri = "mongodb://localhost:27017/"client = AsyncMongoClient(uri)Atlas
以下代码显示了用于连接到Atlas上托管的部署的连接字符串。 选择 Synchronous 或 Asynchronous标签页,查看相应的代码:
uri = "<Atlas connection string>"client = MongoClient(uri, server_api=pymongo.server_api.ServerApi( version="1", strict=True, deprecation_errors=True))uri = "<Atlas connection string>"client = AsyncMongoClient(uri, server_api=pymongo.server_api.ServerApi( version="1", strict=True, deprecation_errors=True))副本集(Replica Set)
以下代码显示了用于连接到副本集的连接字符串。 选择 Synchronous 或 Asynchronous标签页,查看相应的代码:
uri = "mongodb://<replica set member>:<port>/?replicaSet=<replica set name>"client = MongoClient(uri)uri = "mongodb://<replica set member>:<port>/?replicaSet=<replica set name>"client = AsyncMongoClient(uri)网络压缩
以下部分介绍了如何在指定网络压缩算法时连接到MongoDB 。
压缩算法
以下标签页演示了如何在连接到MongoDB时指定所有可用的压缩器:
client = pymongo.MongoClient("mongodb://<db_username>:<db_password>@<hostname>:<port>", compressors = "snappy,zstd,zlib")uri = ("mongodb://<db_username>:<db_password>@<hostname>:<port>/?" "compressors=snappy,zstd,zlib")client = pymongo.MongoClient(uri)client = pymongo.AsyncMongoClient("mongodb://<db_username>:<db_password>@<hostname>:<port>", compressors = "snappy,zstd,zlib")uri = ("mongodb://<db_username>:<db_password>@<hostname>:<port>/?" "compressors=snappy,zstd,zlib")client = pymongo.AsyncMongoClient(uri)要了解有关指定压缩算法的更多信息,请参阅网络压缩指南中的版本兼容性。
zlibCompressionLevel
以下标签页演示了如何为zlib压缩器指定压缩级别:
client = pymongo.MongoClient("mongodb://<db_username>:<db_password>@<hostname>:<port>", compressors = "zlib", zlibCompressionLevel=<zlib compression level>)uri = ("mongodb://<db_username>:<db_password>@<hostname>:<port>/?" "compressors=zlib" "zlibCompressionLevel=<zlib compression level>")client = pymongo.MongoClient(uri)client = pymongo.AsyncMongoClient("mongodb://<db_username>:<db_password>@<hostname>:<port>", compressors = "zlib", zlibCompressionLevel=<zlib compression level>)uri = ("mongodb://<db_username>:<db_password>@<hostname>:<port>/?" "compressors=zlib" "zlibCompressionLevel=<zlib compression level>")client = pymongo.AsyncMongoClient(uri)要了解有关设置 zlib 压缩级别的更多信息,请参阅网络压缩指南中的兼容性。
服务器选择
以下代码显示了指定服务器选择函数的连接字符串。 选择 Synchronous 或 Asynchronous标签页,查看相应的代码:
client = pymongo.MongoClient("mongodb://<db_username>:<db_password>@<hostname>:<port>", server_selector=<selector function>)client = pymongo.AsyncMongoClient("mongodb://<db_username>:<db_password>@<hostname>:<port>", server_selector=<selector function>)要了解有关自定义服务器选择的更多信息,请参阅自定义MongoDB Server选择。
Stable API
以下代码显示了如何为连接指定 Stable API设置。选择 Synchronous 或 Asynchronous标签页以查看相应的代码:
from pymongo.server_api import ServerApi
client = pymongo.MongoClient("mongodb://<db_username>:<db_password>@<hostname:<port>", server_api=ServerApi("<Stable API version>"))from pymongo.server_api import ServerApi
client = pymongo.AsyncMongoClient("mongodb://<db_username>:<db_password>@<hostname:<port>", server_api=ServerApi("<Stable API version>"))要了解有关stable API的更多信息,请参阅stable API 。
限制MongoDB Server执行时间
超时块
以下代码演示如何使用 timeout() 方法设立客户端超时:
with pymongo.timeout(<timeout length>): # perform operations here要了解有关客户端超时的更多信息,请参阅限制MongoDB Server执行时间。
timeoutMS 连接选项
以下标签页演示了如何使用 timeoutMS 连接选项设立客户端超时:
client = pymongo.MongoClient("mongodb://<db_username>:<db_password>@<hostname@:<port>", timeoutMS=<timeout length>)uri = "mongodb://<db_username>:<db_password>@<hostname:<port>/?timeoutMS=<timeout length>"client = pymongo.MongoClient(uri)client = pymongo.AsyncMongoClient("mongodb://<db_username>:<db_password>@<hostname@:<port>", timeoutMS=<timeout length>)uri = "mongodb://<db_username>:<db_password>@<hostname:<port>/?timeoutMS=<timeout length>"client = pymongo.AsyncMongoClient(uri)要了解有关客户端超时的更多信息,请参阅限制MongoDB Server执行时间。