所以。。。问题是csv编写器不理解mongo返回的“子字典”的概念。
如果我理解正确,当你查询Mongo时,你会得到这样一本字典:{
"_id": "a hex ID that correspond with the record that contains several answers",
"answers": [ ... a list with a bunch of dicts in it... ]
}
因此,当csv.DictWriter试图编写它时,它只编写了一个字典(最上面的)。它不知道(也不关心)answers是一个包含字典的列表,这些字典的值也需要写在列中(使用诸如answers.order这样的点符号访问字典中的字段只被Mongo理解,而不是csv编写器)
我知道你应该做的是“浏览”答案列表,并从列表中的每个记录(每个字典)中创建一个字典。一旦您有了一个“platten”字典列表,您就可以传递这些字典并将它们写入您的csv文件中:cursor = client.stack_overflow.stack_039.find(
{}, {'_id': 1, 'answers.order': 1, 'answers.text': 1, 'answers.answerId': 1})
# Step 1: Create the list of dictionaries (one dictionary per entry in the `answers` list)
flattened_records = []
for answers_record in cursor:
answers_record_id