将嵌套对象插入python3中的mongodb中(嵌套对象是类实例)

时间:2019-09-17 05:25:06

标签: python mongodb

我有这样的嵌套结构:


class Student(object):

    def __init__(self, name, age, address):
        self.name = name
        self.age = age
        self.address = address

class Address(object):

    def __init__(self, street, pcode, another_obj):
        self.street = street
        self.postal_code = pcode
        self.another_obj = another_obj

class AnotherObject(object):

    def __init__(self):
        self.someattr = 'some_init_value'


# Now i amm going to save data like this
another_obj = AnotherObject()
address = Address('xyz', 'xyz', another_obj)
obj = Student('abc', 32, address)

对象 obj 是类的实例。我正在做collection.insert_one(obj)。通常,我会执行 obj .__ dict __ 来获取与pymongo兼容的类实例的“ dict”,但它也不会将嵌套对象转换为dict。 这里的问题是“地址”和“ some_other_object”也是其他一些类实例,并且在插入时导致 bson.errors.InvalidDocument 异常。

是否可以将嵌套的类实例/文档(地址和some_other_object)转换为dict或mongodb可接受的任何其他类型。

我用于mongodb通信的软件包是pymongo v3.9.0。

错误是TypeError:文档必须是dict,bson.son.SON,bson.raw_bson.RawBSONDocument的实例,或者是从collections.MutableMapping继承的类型

1 个答案:

答案 0 :(得分:0)

在您的类中添加一些to_dict()方法:

from pymongo import MongoClient


class Student(object):

    def __init__(self, name, age, address):
        self.name = name
        self.age = age
        self.address = address

    def to_dict(self) -> dict:
        record = {
            "name": self.name,
            "age": self.age,
            "address": self.address.to_dict() if self.address is not None else None
        }
        return record


class Address(object):

    def __init__(self, street, pcode, another_obj):
        self.street = street
        self.postal_code = pcode
        self.another_obj = another_obj

    def to_dict(self) -> dict:
        record = {
            "street": self.street,
            "postal_code": self.postal_code,
            "another_obj": self.another_obj.to_dict() if self.another_obj is not None else None
        }
        return record


class AnotherObject(object):

    def __init__(self):
        self.someattr = 'some_init_value'

    def to_dict(self) -> dict:
        record = {
            "someattr": self.someattr
        }
        return record


# Now i amm going to save data like this
another_obj = AnotherObject()
address = Address('xyz', 'xyz', another_obj)
obj = Student('abc', 32, address)
db = MongoClient()['yourdatabase']
db.collection.insert_one(obj.to_dict())
print(db.collection.find_one({}))