You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB文档删除方法实现及AttributeError与返回内容问题解决

解决AnimalShelter类的delete方法AttributeError问题并返回删除文档的JSON

问题根源

  • 语法错误:delete方法定义行def delete(self, data)末尾缺少冒号:,导致Python无法正确解析该方法,类实例自然无法识别delete属性。
  • 当前实现仅打印操作结果,未按需求返回被删除文档的JSON格式内容。

修复后的代码实现

修改animal_shelter.py中的delete方法,同时添加必要的导入以处理MongoDB文档的JSON序列化:

from pymongo import MongoClient
from bson.objectid import ObjectId
import json
from bson import json_util  # 新增:用于序列化MongoDB特殊数据类型

class AnimalShelter(object):
    """ CRUD operations for Animal collection in MongoDB """

    def __init__(self,username,password):
        self.client = MongoClient('mongodb://localhost:55996')
        self.database = self.client['AAC']

    # 保留其他create、read、update方法不变...

    # Delete method to implement the D in CRUD
    def delete(self, data):  # 修复:添加缺失的冒号
        result = self.database.animals.find_one_and_delete(data)
        if result:
            # 将MongoDB文档转换为标准JSON字符串
            return json.dumps(result, default=json_util.default)
        else:
            # 无匹配文档时返回提示JSON
            return json.dumps({"status": "success", "message": "Nothing to delete"})

测试代码调整

在testing_script.ipynb中可以接收并打印返回的JSON结果:

# Calls the delete function
deleted_json = shelter.delete(data)
print(deleted_json)

关键说明

  • find_one_and_delete()会直接返回被删除的完整文档(若找到匹配项),否则返回None,刚好满足返回删除文档的需求。
  • 使用bson.json_util是因为MongoDB文档包含ObjectId这类Python标准JSON无法序列化的类型,该工具可以自动处理这些特殊类型。
  • 如果不需要返回JSON字符串,而是返回Python字典对象,直接返回result或{"status": "success", "message": "Nothing to delete"}即可。

内容的提问来源于stack exchange,提问作者FireMonkey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 00:10:49