Reputation: 707
Objective : I wanted to insert more than one value in a single document.
Following is an example program, were I need to insert value to MongoDB collection's document
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)}
but if "stackf" got any return value - this code doesn't write anything.
Upvotes: 0
Views: 1792
Reputation: 50406
You seem to be talking about a "list" of "lists" that you want to transform into a "list" of "dict".
So basically
listOfList = [[1,2],[3,4],[5,6]]
map(lambda x: { "OrginalName": x[0], "ExportPath": x[1] }, listOfList )
Produces:
[
{'ExportPath': 2, 'OrginalName': 1},
{'ExportPath': 4, 'OrginalName': 3},
{'ExportPath': 6, 'OrginalName': 5}
]
So you can use that to construct your statement without trying to look as in:
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)
Not sure what the "index" values meant to you other than looking up the current "Attachment" values. But this will insert a new document for every "messsage" and put all the "Attachments" in an array of that document matching your new dict structure.
Upvotes: 1