FastAPI使用异步motor实现对mongodb的增删改查
    		       		warning:
    		            这篇文章距离上次修改已过429天,其中的内容可能已经有所变动。
    		        
        		                
                
from fastapi import FastAPI
from motor.motor_asyncio import AsyncIOMotorClient
 
app = FastAPI()
 
# 连接到MongoDB
client = AsyncIOMotorClient("mongodb://localhost:27017")
database = client.get_database('example_db')
motor_collection = database.get_collection('example_collection')
 
# 创建文档
async def create_item(item: dict):
    await motor_collection.insert_one(item)
 
# 获取文档
async def get_items():
    items = []
    async for item in motor_collection.find():
        items.append(item)
    return items
 
# 删除文档
async def delete_item(item_id):
    result = await motor_collection.delete_one({"_id": item_id})
    return result.deleted_count
 
# 更新文档
async def update_item(item_id, item: dict):
    result = await motor_collection.update_one({"_id": item_id}, {"$set": item})
    return result.modified_count
 
# 示例路由
@app.get("/items/")
async def read_items():
    return await get_items()
 
@app.post("/items/")
async def create_item(item: dict):
    await create_item(item)
    return item
 
@app.delete("/items/{item_id}")
async def delete_item(item_id):
    deleted_count = await delete_item(item_id)
    return {"deleted_count": deleted_count}
 
@app.put("/items/{item_id}")
async def update_item(item_id: str, item: dict):
    modified_count = await update_item(item_id, item)
    return {"modified_count": modified_count}这段代码展示了如何使用FastAPI框架和异步motor客户端来实现对MongoDB的基本增删改查操作。代码中的函数都是异步的,这使得它们能够很好地与FastAPI的异步特性集成。在实际应用中,你需要根据自己的需求对这些函数进行适当的修改和扩展。
评论已关闭