【发布时间】:2020-12-21 02:40:35
【问题描述】:
假设我有以下 mongo 模型:
class User(Document):
name = StringField(required=True,unique=True)
characteristics = DictField()
class Office(Document):
user = ReferenceField(User)
office= StringField(required=True,unique=True)
salary = IntField()
class Department(Document):
offices = ReferenceField(Office)
city = StringField(required=True,unique=True)
country = StringField()
我有以下数据框:
df_users = pd.DataFrame({"name":["Goku","Gohan","Piccolo"],
"characteristics":[{"a":1},{"b":2},{"c":3}]})
df_office = pd.DataFrame({"user":["Goku","Gohan","Piccolo"],
"office":["Earth","Pao","Namek"],
"salary":[1,2,3]})
df_department = pd.DataFrame({"offices":["Earth","Pao","Namek"],
"city":["South City","North City","nameki"],
"country":["A","B","C"] })
我知道我可以轻松地将这些数据帧上传到 mongo 集合:
db.collection.insert_many(df_name.to_dict("records"))
但如果我这样做了,那么为什么我要定义这些类 User、Office、Department?我不知道我是否会得到非空答案
User.objects(); Office.objects(), Department.objects()
我知道我能做到
记录 = 用户(名称 = “悟空”,特征 = 0) record.save # 一些命令上传到集合
所以,我的问题是,如何使用我定义的类上传这些数据帧? 某种
df_name.apply(lambda x: Respectively_Class(**x)).insert(db.collection_name)
所以当我调用 Respectively_Class.objects 时,我得到了一个非空结果?
【问题讨论】:
标签: python mongodb pymongo mongoengine