FastAPI删除mongodb重复数据(数据清洗)

在 FastAPI 中删除 MongoDB 重复数据,你需要结合使用 MongoDB 查询和 FastAPI 的路由功能。以下是一个通用的例子,演示如何删除特定字段上的重复数据:

1. 定义数据模型:

python 复制代码
from pydantic import BaseModel, Field
from bson import ObjectId
from typing import Optional

class PyObjectId(ObjectId):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v):
        if not ObjectId.is_valid(v):
            raise ValueError("Invalid objectid")
        return ObjectId(v)

    @classmethod
    def __modify_schema__(cls, field_schema):
        field_schema.update(type="string")

class ItemBase(BaseModel):
    field_to_check: str # 需要检查重复的字段

class Item(ItemBase):
    id: Optional[PyObjectId] = Field(alias="_id")

    class Config:
        arbitrary_types_allowed = True
        json_encoders = {ObjectId: str}

2. 创建 MongoDB 连接:

python 复制代码
from motor.motor_asyncio import AsyncIOMotorClient

MONGO_DETAILS = "mongodb://localhost:27017" # 替换为你的 MongoDB 连接字符串
client = AsyncIOMotorClient(MONGO_DETAILS)
database = client["your_database_name"] # 替换为你的数据库名称
collection = database.get_collection("your_collection_name") # 替换为你的集合名称

3. 实现删除逻辑:

python 复制代码
from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.delete("/items/duplicates/", response_model=list[Item])
async def delete_duplicate_items(field_name: str = "field_to_check"):
    """
    删除指定字段上的重复数据。

    Args:
        field_name (str, optional): 需要检查重复的字段名. Defaults to "field_to_check".

    Returns:
        list[Item]: 返回删除的重复文档列表.
    """
    # 使用聚合管道查找并删除重复项
    pipeline = [
        {"$match": {"version": 1}},  # 只处理 version 为 1 的文档
        {"$group": {"_id": {"{}".format(field_name): "$"+field_name}, "count": {"$sum": 1}, "dups": {"$push": "$_id"}}},
        {"$match": {"count": {"$gt": 1}}},
        {"$unwind": "$dups"},
        {"$skip": 1}, 
        {"$project": {"_id": "$dups"}}
    ]

    duplicate_ids = [doc["_id"] async for doc in collection.aggregate(pipeline)]
    if duplicate_ids:
        deleted_items = []
        for item_id in duplicate_ids:
            result = await collection.find_one_and_delete({"_id": item_id})
            if result:
                deleted_items.append(Item(**result))
        return deleted_items

    raise HTTPException(status_code=404, detail="没有找到重复数据")

4. 运行 FastAPI 应用:

bash 复制代码
uvicorn main:app --reload

解释:

  • 数据模型: 使用 Pydantic 定义数据模型,确保数据一致性.
  • MongoDB 连接: 使用 motor 库异步连接到 MongoDB 数据库.
  • 聚合管道: 使用 MongoDB 的聚合管道查找重复数据:
    • $group: 按指定字段分组,计算每个分组中文档数量.
    • $match: 筛选数量大于 1 的分组,即存在重复数据的组.
    • $unwind: 将 dups 数组展开为多行.
    • $skip: 跳过每组的第一个文档,因为我们只删除重复的.
    • $project: 只保留 _id 字段.
  • 删除数据: 使用 find_one_and_delete 方法删除找到的重复文档.
  • 错误处理: 如果没有找到重复数据,抛出 404 错误.

注意:

  • 将代码中的占位符替换为你自己的数据库和集合名称.
  • 可以根据需要修改聚合管道,以适应不同的重复数据查找需求.
相关推荐
前端精髓20 小时前
结构化输出with_structured_output(抽卡)
python·langchain
尹人入圣21 小时前
目前热门的IP驱动产业新场景新工具
网络·python·网络协议·tcp/ip
Nuanyt1 天前
Agent 学习笔记(下篇三):上线工程、进阶选择与操作界面(Stage 7 / 7.5 / 8 + 延伸路线)
笔记·python·学习·memory·aiagent·harness
吴卫斌1 天前
定投ETF实战指南(四):行业/主题ETF——定投的“进攻端“
开发语言·python·股票·量化
2601_967987371 天前
Python——入门级(定义功能def函数)
python·函数·可变参数·默认参数·关键字参数
专注仿真1 天前
梯度提升类(XFBoost)算法详解与代码实例
开发语言·人工智能·python·算法·大模型训练·控制算法
外收内放1 天前
Python基础语法练习题(75)
开发语言·python·学习
黑十1 天前
PyTorch 报 “no CUDA GPUs are available“ 怎么办?3 步排查
服务器·网络·人工智能·pytorch·python
threelab1 天前
开源图片去水印代码
python
taller_20001 天前
【012】数据类型入门: Excel 数据到 Python 值的转换
python·excel·pie·py