【发布时间】:2020-09-15 04:40:21
【问题描述】:
免责声明:我是 mongo 的新手..
所以我将这些数据从我正在处理为“python 字典”格式的文本文件中获取,以便可以将其插入到我使用 Pymongo 创建的集合中。
原始数据已更改为文本,抱歉...可以在 pastebin 上查看 Link to raw data text
这是python中用于插入的格式化字典
[{'Poll_Name': 'ECU', 'Date': '2020-05-07', 'Sample_Size': '--', 'MoE': '--', 'Biden (D)': '46', 'Trump(R)': '43', 'Spread': 'Trump +3'}, {'Poll_Name': 'WRAL-TV', 'Date': '2020-04-23', 'Sample_Size': '580 LV', 'MoE': '5.5', 'Biden (D)': '45', 'Trump(R)': '50', 'Spread': 'Biden +5'}, {'Poll_Name': 'PPP (D)', 'Date': '2020-04-14', 'Sample_Size': '1318 RV', 'MoE': '2.7', 'Biden (D)': '47', 'Trump(R)': '48', 'Spread': 'Biden +1'}, {'Poll_Name': 'Civitas', 'Date': '2020-04-05', 'Sample_Size': '500 LV', 'MoE': '4.4', 'Biden (D)': '49', 'Trump(R)': '42', 'Spread': 'Trump +7'}]
我已将所有字典数据插入到一个数组中,我打算用它进行 insertmany()。
这是我目前以字典格式导出此数据的代码
def export_Data(filename):
export_List = [] #list that will contain the dictionary values of the data
key_List = ["Poll_Name", "Date", "Sample_Size", "MoE", "Biden (D)", "Trump(R)", "Spread"] #list of keys for each value
count = 0
temp_List = []
with(open(filename, "r")) as infile: #opening the file of raw data
for line in infile:
count += 1
temp_List.append(line.strip("\n")) #i add each line of infile to this temporary list
if count % len(key_List) == 0: #when 7 items are added
temp_dict = {} #create a temporary dictionary
for key, line in zip(key_List, temp_List): #fill in dictionary key values..
temp_dict[key] = line
temp_List = [] # resetting the temporary dictionary
export_List.append(temp_dict) #appending dictionary to final list
print(export_List)
#export the list later once i get properly formatted..
现在您可以看到在文本文件和字典示例中找到的一些条目被视为“--”,这些条目假定代表空/空值。 我想将这些值作为 null 而不是“--”插入到我的数据库中,以避免在 mongo 中进行大规模更新查询,我觉得它可能会使数据清理/导出过程更简单、更快。 有什么办法可以更改这些值,以便可以将它们插入为 null 而不是“--” 将不胜感激任何解决方案,我知道可能有一个简单的答案!但是这个新手希望得到一些澄清。
【问题讨论】:
-
我们能看到处理文本的代码吗?在 MongoDB 中,字段为空、未定义和不存在也是不同的。这可能很重要,具体取决于您计划如何索引和查询这些数据。
-
如果您将文本作为文本复制粘贴到问题中,查看文本也容易得多。屏幕截图只能在相同大小的屏幕上看起来正确,因此在移动设备上查看它们真的很痛苦。
-
对不起,我把它改成了文本,希望对你有帮助。谢谢你陪我。还在导出时添加了一些额外的代码
-
我对 mongo 中的 null 值一点也不熟悉,如果有任何关于它们如何工作的资源或解释,我将不胜感激。甚至不知道它们会影响索引和查询数据
标签: python python-3.x mongodb performance pymongo