Python 如何跳过重复索引错误并继续在MongoDB(pymongo)中进一步添加文档
我正在将csv文件中的数据加载到mongoDB中。首先,我下载了一个文档来设置集合索引。成功了 现在我加载其余的文档,并且有一行被复制,即它已经在数据库中,并且在我的文档中。我得到错误11000,如何绕过它,跳过重复行并加载下一行 作为我文件的一小部分,它每天都在更新,需要导入数据库Python 如何跳过重复索引错误并继续在MongoDB(pymongo)中进一步添加文档,python,csv,indexing,import,pymongo,Python,Csv,Indexing,Import,Pymongo,我正在将csv文件中的数据加载到mongoDB中。首先,我下载了一个文档来设置集合索引。成功了 现在我加载其余的文档,并且有一行被复制,即它已经在数据库中,并且在我的文档中。我得到错误11000,如何绕过它,跳过重复行并加载下一行 作为我文件的一小部分,它每天都在更新,需要导入数据库 date confirmed deaths recovered region_code isolation_start level 0 2021-01-23 12
date confirmed deaths recovered region_code isolation_start level
0 2021-01-23 12638.0 113.0 10710.0 RU-AD 16.07.2020 21:58:11 3.0
1 2021-01-23 37509.0 1106.0 34026.0 RU-ALT 25.09.2020 10:16:19 3.0
2 2021-01-23 18698.0 130.0 16809.0 RU-AMU 21.08.2020 09:22:04 2.0
3 2021-01-23 49257.0 458.0 41291.0 RU-ARK 31.07.2020 08:45:20 2.0
4 2021-01-23 23072.0 467.0 14547.0 RU-AST 23.06.2020 14:29:27 2.0
字段必须设置为索引:日期、地区\代码
我的尝试
def Insert(self, path=None, parse_dates=None, dtype=None, skiprows=None, astype=None):
for df in tqdm(range(1)):
df = pd.read_csv(path)
data = df.to_dict('records')
self.collection.create_index(('date', 'region_code'),unique=True)
self.collection.insert_many(data)
if __name__ == "__main__":
mongodb = MongoDB(dBName='test_import', collectionName='myimport2')
mongodb.Insert(path="C:/Users/tred1/Desktop/aggregation_RU_last_day.csv")
我得到这个错误
BulkWriteError: batch op errors occurred, full error: {'writeErrors': [{'index': 0, 'code': 11000, 'keyPattern': {'date': 1},
'keyValue': {'date': '2021-01-23'}, 'errmsg': 'E11000 duplicate key error collection: test_import.myimport2 index: date_1 dup key: { date: "2021-01-23" }',
'op': {'date': '2021-01-23', 'confirmed': 12638.0, 'deaths': 113.0, 'recovered': 10710.0, 'region_name': 'Республика Адыгея', 'region_code': 'RU-AD', 'isolation_start': '16.07.2020 21:58:11', 'level': 3.0, 'self_isolation': nan,
'_id': ObjectId('60117910ae27c82c91526449')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0,
'upserted': []}
如何将其添加到异常中?可能很简单,但在文档中找不到它有两种选择:
insert_one()
,包装为try/except;忽略BulkWriteErrorinsert_many()
并使用ordered=False
标志嗨,很抱歉现在评论。我还有一个问题。当执行
collection.insert_many(df2,ordered=False)
getpymongo.errors.BulkWriteError:batch op错误发生时,完整错误:{'writeErrors':[{'index':0,'code':11000,'keyPattern':{'date':1}…
。我不能忽略错误,可能我不理解某些内容。我将把代码添加到新的“答案”中,请查看如何在此文档中添加通行证。我找到了答案,朋友。事实上,我最初设置的索引设置错误,这就是问题所在,一切正常,谢谢。)