1
我想在我的收藏中登录insert_many()
文档。其中一些可能与集合中的现有文档具有相同的键/值对(在我的示例中为screen_name
)。我在这个键上有一个唯一的索引集,因此我得到一个错误。Pymongo:insert_many +唯一索引
my_collection.create_index("screen_name", unique = True)
my_collection.insert_one({"screen_name":"user1", "foobar":"lalala"})
# no problem
to_insert = [
{"screen_name":"user1", "foobar":"foo"},
{"screen_name":"user2", "foobar":"bar"}
]
my_collection.insert_many(to_insert)
# error :
# File "C:\Program Files\Python\Anaconda3\lib\site-packages\pymongo\bulk.py", line 331, in execute_command
# raise BulkWriteError(full_result)
#
# BulkWriteError: batch op errors occurred
我想:
- 没有得到一个错误
- 不会改变已经存在的文件(这里
{"screen_name":"user1", "foobar":"lalala"}
) - 插入所有非现有的文件(在这里,
{"screen_name":"user2", "foobar":"bar"}
)
编辑:正如有人在评论中所说的“这个问题是要求如何做批量插入和忽略唯一索引错误,同时仍插入成功的记录。因此它不是这样一个问题重复我怎么做批量插入”请重新打开它