今天在爬水滴筹数据的时候写入mongodb的时候遇见了这个情况,内容如下:
for item in dict_infor["data"]:
if self.judge_patient(name, **item):
my_infor["project_id"] = project_id
my_infor["name"] = name
my_infor["shuidi_infor"] = item
conn["admin"].shuidi_rasing.insert(my_infor)
with open("result.txt", "a+") as f:
f.write(str(project_id)+"\t"+name+"\n")
写入一条之后一直报错,说的是id主键冲突,找了半天终于解决了,只需要在写入的内容上加一个copy()即可。
代码改成如下:
for item in dict_infor["data"]:
if self.judge_patient(name, **item):
my_infor["project_id"] = project_id
my_infor["name"] = name
my_infor["shuidi_infor"] = item
conn["admin"].shuidi_rasing.insert(my_infor.copy())
with open("result.txt", "a+") as f:
f.write(str(project_id)+"\t"+name+"\n")
另外附上原文链接。希望能对遇见这个问题的同学有帮助。
https://stackoverflow.com/questions/17529216/mongodb-insert-raises-duplicate-key-error