Docs 菜单
Docs 主页
/ /

Motor(异步驱动程序)

欢迎访问Motor的文档站点,Motor 是异步Python应用程序的官方MongoDB驱动程序。使用 pip 下载,或按照我们的教程设立可运行的项目。

提示

如果不需要以非阻塞方式或使用协同程序访问 MongoDB,我们建议改用 PyMongo 驱动程序。

请访问以下链接阅读博客文章,这些文章描述了 Motor 驱动程序的具体用例:

您必须安装 Motor 驱动程序模块才能使其可供您的 Python 应用程序使用。我们推荐使用 pip 安装 Motor。

以下命令演示了如何使用命令行安装最新版本的模块:

$ python -m pip install motor

要详细了解相关要求和其他安装方法,请参阅 Motor 安装文档。

您可以使用以下连接片段,通过 asyncio 异步框架来测试与 Atlas 上 MongoDB 部署的连接:

import asyncio
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo.server_api import ServerApi
async def ping_server():
# Replace the placeholder with your Atlas connection string
uri = "<connection string>"
# Set the Stable API version when creating a new client
client = AsyncIOMotorClient(uri, server_api=ServerApi('1'))
# Send a ping to confirm a successful connection
try:
await client.admin.command('ping')
print("Pinged your deployment. You successfully connected to MongoDB!")
except Exception as e:
print(e)
asyncio.run(ping_server())

此连接代码段使用 Stable API 功能,可以在使用 Motor 驱动程序 v2.5 (及更高版本)连接到 MongoDB Server v5.0 (及更高版本)时启用该功能。使用此功能时,您可以更新驱动程序或服务器,无需担心任何 Stable API 所支持命令的向后兼容性问题。

如需了解有关“Stable API”功能的更多信息,请参阅“服务器”手册中的“Stable API”。

注意

从 2022 年 2 月开始,版本化 API被称为 Stable API。此次命名更改后,所有概念和功能均保持不变。

如果您使用的 MongoDB 版本或驱动程序不支持“稳定 API”功能,您可以使用以下代码片段来测试与 Atlas 上的 MongoDB 部署的连接:

import asyncio
from motor.motor_asyncio import AsyncIOMotorClient
async def ping_server():
# Replace the placeholder with your Atlas connection string
uri = "<connection string>"
# Create a new client and connect to the server
client = AsyncIOMotorClient(uri)
# Send a ping to confirm a successful connection
try:
await client.admin.command('ping')
print("Pinged your deployment. You successfully connected to MongoDB!")
except Exception as e:
print(e)
asyncio.run(ping_server())

如果您使用的是 tornado 异步库,则可使用以下代码连接到 MongoDB 部署:

import tornado
import motor
async def ping_server():
# Replace the placeholder with your Atlas connection string
uri = "<connection string>"
# Set a 5-second connection timeout when creating a new client
client = motor.motor_tornado.MotorClient(uri, serverSelectionTimeoutMS=5000)
# Send a ping to confirm a successful connection
try:
await client.admin.command('ping')
print("Pinged your deployment. You successfully connected to MongoDB!")
except Exception as e:
print(e)
tornado.ioloop.IOLoop.current().run_sync(ping_server)

如果您需在本地机器上运行 MongoDB 服务器以用于开发目的而不是使用 Atlas 集群,则需完成以下操作:

  1. 下载 MongoDB Server CommunityEnterprise 版本。

  2. 安装并配置 MongoDB Server。

  3. 启动该服务器。

重要

务必保护您的 MongoDB 服务器免受恶意攻击。请参阅我们的安全检查清单,获取安全建议清单。

在成功启动 MongoDB 服务器后,在驱动程序连接代码中指定连接字符串。

如果 MongoDB Server 在本地运行,您可以使用连接字符串 "mongodb://localhost:<port>",其中 <port> 是您配置服务器以侦听传入连接的端口号。

如果您需要指定不同的主机名或 IP 地址,请参阅 Server 手册中有关连接字符串的条目。

要测试是否能够连接到服务器,请替换连接到 MongoDB Atlas 示例代码中的连接字符串,并运行此代码。

有关 Motor 与MongoDB Server和Python 的兼容性的信息,请参阅兼容性页面。

后退

版本兼容性

在此页面上