2017-06-17 110 views
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 

我想:

  1. 没有得到一个错误
  2. 不会改变已经存在的文件(这里{"screen_name":"user1", "foobar":"lalala"}
  3. 插入所有非现有的文件(在这里, {"screen_name":"user2", "foobar":"bar"}

编辑:正如有人在评论中所说的“这个问题是要求如何做批量插入和忽略唯一索引错误,同时仍插入成功的记录。因此它不是这样一个问题重复我怎么做批量插入”请重新打开它

回答

3

一种解决方案可能是使用的insert_manyordered参数,并将其设置为False(默认为True):

my_collection.insert_many(to_insert, ordered=False) 

From the PyMongo documentation:

有序(可选):如果True(默认),文件将被插入 在服务器上按顺序提供。如果发生错误,所有 剩余的插入被中止。如果False,文件将以 服务器的任意顺序插入,可能并行,,并且所有文档将会尝试插入文件 。

虽然,当所有文档无法插入时仍然需要处理异常。

根据您的使用情况,您可以决定输入pass,记录警告或检查异常。