从Python中的另一个对象创建对象



我想将MongoDB中的一些文档从一个数据库复制到另一个数据库,但只复制该文档的特定属性。给定一个格式为的源文档

{topic: string, email: {enabled: boolean}, mobile: {enabled: boolean}}

我想在新的数据库中插入以下格式的东西:

{topic: string, email: {enabled: boolean}}

我正在做这样的事情,以便创建将要插入的新对象:

class Document(object):
topic = ""
email = object()
def make_document(topic, email):
document = Document()
document.topic = topic
document.email = email
return document
settings = source_db.collectionName.find({})
for setting in settings:
new_setting = make_document(setting.topic, setting.email)
db.collectionName.insertOne(new_setting)

我的疑虑是:

  • 我是否正确创建了新对象
  • 类中电子邮件属性的声明是否正确(例如,email=object(((
  • 有更好(或更正确(的方法吗

我对Python真的很陌生。

这是初始化类中变量(类属性(的正确方法,

class Document(object):
def __init__(self, topic, email):
self.topic = topic
self.email = email
settings = source_db.collectionName.find({})
for setting in settings:
new_setting = Document(setting.topic, setting.email)
db.collectionName.insertOne(new_setting)

问题:既然你得到的回复是dictionary/json,你为什么要把它作为类?

{topic: string, email: {enabled: boolean}, mobile: {enabled: boolean}}

更新:然后您可以简单地通过字典解析来实现这一点。检查这个,

settings = source_db.collectionName.find({})
for setting in settings:
new_data = {"topic": setting["topic"], "email": setting["email"]}
db.collectionName.insertOne(new_data)

最新更新