使用 python 在 mongodb 中插入嵌套值

Insert nested value in mongodb using python

Objective :我想在单个文档中插入多个值。

下面是一个示例程序,我需要向 MongoDB 集合的文档中插入值吗

for message in mbox:
    stackf = getattachements(message)
    if len(stackf) > 0:
        for i in range(len(stackf)):
            print stackf[i][0]
            print stackf[i][1]
            post = {'sl':i,'From' : message['From'],'To' : message['To'], 'Date' : message['Date'],'Subject' : message['subject'],'Body' : getbody(message),'Attachement' : [{"Originalname" :stackf[i][0],"Exportpath" : stackf[i][1]}]}
    else:
            post = {'sl':i,'From' : message['From'],'To' : message['To'], 'Date' : message['Date'],'Subject' : message['subject'],'Body' : getbody(message)}

但如果 "stackf" 得到任何 return 值 - 此代码不写入任何内容。

您似乎在谈论要将 "lists" 的 "list" 转换为 "dict" 的 "list"。

所以基本上

listOfList = [[1,2],[3,4],[5,6]]
map(lambda x: { "OrginalName": x[0], "ExportPath": x[1] }, listOfList )

生产:

[         
    {'ExportPath': 2, 'OrginalName': 1}, 
    {'ExportPath': 4, 'OrginalName': 3},
    {'ExportPath': 6, 'OrginalName': 5}
]

因此您可以使用它来构建您的陈述,而无需尝试看起来像:

for message in mbox:
    post = { 
       'From' : message['From'],
       'To' : message['To'],
       'Date' : message['Date'],
       'Subject' : message['subject'],
       'Body' : getbody(message)
    }
    stackf = getattachements(message)
    if len(stackf) > 0:
        mapped = map(lambda x: { "OrginalName": x[0], "ExportPath": x[1] }, stackf )
        post['Attachement'] = mapped

    collection.insert_one(post)

除了查找当前的 "Attachment" 值外,不确定 "index" 值对您意味着什么。但这将为每个 "messsage" 插入一个新文档,并将所有 "Attachments" 放入与您的新字典结构匹配的文档数组中。