【问题标题】:pymongo error document must be an instance of dictpymongo 错误文档必须是 dict 的实例
【发布时间】:2021-06-20 10:06:35
【问题描述】:

我正在尝试将一个对象放入集合中,但我收到错误消息:

raise TypeError("%s must be an instance of dict, bson.son.SON, "
TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping

我的代码如下所示:

class DataBase:

    def __init__(self):
        self.myclient = pymongo.MongoClient("mongodb://localhost:27018/")
        self.mydb = self.myclient["MMA_TOURNAMNET"]
        self.tournamnets = self.mydb["tournamnets"]

    def insert_new_tournamnet(self, tournament):
        jason_tour = json.dumps(tournament.__dict__)
        print(jason_tour)
        self.tournamnets.insert_one(jason_tour)

我调用这个类的一个函数,比如:self.data_base.insert_new_tournamnet(tour)

旅游对象变换后的形式为:

{"list_fighters": [{"Name": "Barry Boday", "Test Status": 0, "Weeks in Bubble": 0}, {"Name": "Steve Vaughn", "Test Status": 0, "Weeks in Bubble": 0}, {"Name": "Jack Zink", "Test Status": 1, "Weeks in Bubble": 0}], "schedule_list": [[{"Name": "Barry Boday", "Test Status": 0, "Weeks in Bubble": 0}, {"Name": "Steve Vaughn", "Test Status": 0, "Weeks in Bubble": 0}]]}

作为 Json 格式放入集合中似乎很好。但我无法摆脱错误。有什么想法吗?

【问题讨论】:

  • 您不需要将对象序列化为json,只需传递dict

标签: python json mongodb pymongo


【解决方案1】:

只需将您的记录保留为 dict 并将其传递给 insert_one()

def insert_new_tournamnet(self, tournament):
    self.tournamnets.insert_one(tournament.__dict__)

【讨论】:

    猜你喜欢
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多