目录:
Motor 是 MongoDB 官方推出的异步 Python 驱动程序,作为 yMongo 的异步版本,它专为现代异步编程而设计,支持 asyncio 和 Tornado 框架,能显著提升 I/O 密集型应用的并发处理能力。
Motor 基于asyncio 构建,利用协程机制,使得单个线程即可处理数千个并发数据库操作,通过事件循环(如 Linux 的 epoll)调度 I/O 任务,避免了线程切换的开销,实现了高效的资源复用。
Motor 要求 Python 版本在 3.5.3 或更高。
$ pip install motor
import motor.motor_asyncio
# 创建异步客户端
client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://localhost:27017')
# 获取数据库和集合(此操作不执行 I/O,无需 await)
db = client.test_database
collection = db.users
支持单条插入 (insert_one) 和批量插入 (insert_many)。
async def insert_example():
# 插入单条文档
result = await collection.insert_one({"name": "John", "age": 30})
print(f'插入文档ID: {result.inserted_id}')
# 批量插入文档
docs = [{"name": f"user_{i}"} for i in range(5)]
result = await collection.insert_many(docs)
print(f'批量插入数量: {len(result.inserted_ids)}')
使用 find_one 查询单条记录,或使用 find 返回一个异步游标进行迭代
async def query_example():
# 查询单个文档
doc = await collection.find_one({"name": "John"})
print(doc)
# 使用异步游标查询多个文档
cursor = collection.find({"age": {"$gte": 25}})
async for document in cursor:
print(document)
# 也可以将游标转换为列表(注意数据量)
docs_list = await cursor.to_list(length=100)
async def update_example():
# 更新文档
update_result = await collection.update_one(
{"name": "John"},
{"$set": {"age": 31}}
)
print(f'修改了 {update_result.modified_count} 个文档')
async def update_and_delete():
# 删除文档
delete_result = await collection.delete_one({"name": "John"})
print(f'删除了 {delete_result.deleted_count} 个文档')
async def aggregate_example():
pipeline = [
{"$group": {"_id": "$age", "count": {"$sum": 1}}},
{"$sort": {"count": -1}}
]
async for doc in collection.aggregate(pipeline):
print(f"年龄 {doc['_id']}: {doc['count']} 人")
↶ 返回首页 ↶